2022 EssentialsSwiftUI & UI Frameworks
WWDC22 · 24 min · Essentials / SwiftUI & UI Frameworks
What’s new in TextKit and text views
Discover the latest updates to TextKit and text views in UI frameworks. Explore layout refinements and API enhancements, learn how you can maintain compatibility across multiple OS versions, and find out how to modernize your app with TextKit 2. To get the most out of this session, watch “Meet TextKit 2” from WWDC21.
Watch at developer.apple.com ↗Code shown on screen · 5 snippets
Check for NSTextLayoutManager first
if let textLayoutManager = textView.textLayoutManager {
// TextKit 2 code goes here
}
else {
let layoutManager = textView.layoutManager
// TextKit 1 code goes here
} Counting number of lines of wrapped text in a text view with TextKit 2
// Example: Updating glyph-based code
var numberOfLines = 0
let textLayoutManager = textView.textLayoutManager
textLayoutManager.enumerateTextLayoutFragments(from:
textLayoutManager.documentRange.location,
options: [.ensuresLayout]) { layoutFragment in
numberOfLines += layoutFragment.textLineFragments.count
} Convert NSRange to NSTextRange
let textContentManager = textLayoutManager.textContentManager
let startLocation = textContentManager.location(textContentManager.documentRange.location,
offsetBy: nsRange.location)!
let endLocation = textContentManager.location(startLocation,
offsetBy: nsRange.length)
let nsTextRange = NSTextRange(location: startLocation, end: endLocation) Convert NSTextRange to NSRange
let textContentManager = textLayoutManager.textContentManager
let location = textContentManager.offset(from: textContentManager.documentRange.location,
to: nsTextRange!.location)
let length = textContentManager.offset(from: nsTextRange!.location,
to: nsTextRange!.endLocation)
let nsRange = NSRange(location: location, length: length) Convert UITextRange to NSTextRange
let offset = textView.offset(from: textview.beginningOfDocument, to: uiTextRange.start)
let startLocation = textContentManager.location(textContentManager.documentRange.location,
offsetBy: offset)!
let nsTextRange = NSTextRange(location: startLocation) Related sessions
-
24 min -
41 min