AttributedString 有那些改變?

Asked on 06/12/2025

1 search

在 WWDC 2025 的 "Code-along: Cook up a rich text experience in SwiftUI with AttributedString" 會議中,AttributedString 有以下幾個改變和新功能:

  1. 支持多種字符視圖:AttributedString 現在提供了對 UTF8 和 UTF16 標量的視圖,這些視圖與現有的字符視圖共享相同的索引。

  2. 變換功能:引入了一個 transform 函數,允許在給定範圍內對 AttributedString 進行就地變換,並在變換結束後更新範圍的索引。

  3. 自定義屬性和約束:可以定義自定義的 AttributedString 屬性,並通過 AttributedStringKey 協議提供的 API 來限制屬性值的變化,確保屬性與文本內容保持一致。

  4. 支持豐富文本編輯:SwiftUI 的 Text Editor 現在支持 AttributedString,允許使用內建的文本格式化控件進行豐富文本編輯。

  5. 改進的索引管理:在變更 AttributedString 時,會自動更新索引以避免無效的選擇或崩潰。

這些改變使得 AttributedString 在 SwiftUI 中的應用更加靈活和強大,特別是在處理豐富文本和自定義文本格式時。

如果你想了解更多細節,可以查看 Code-along: Cook up a rich text experience in SwiftUI with AttributedString 的 "TextEditor and AttributedString" 章節。