Adding Writing Tools to your custom views requires two components. The first necessary component is the UITextInteraction. This class is not Writing Tools specific. It was released in iOS 13 and allows the end user to perform selection gestures on your custom text views.
Hdogagn Zoinl ag izufbek ny cra aywunoun oy a EUDuxvEyyofavwaum obl ey uyen kco IUHiqxErsot jhikokuv wu teywacm yi ibiszl.
Preparing up a class for Writing Tools
The first thing you need to do is to adopt the UITextInput protocol. Here is a custom text view. Notice that it is a UIView and it also implements the UITextInput protocol.
var selectedTextRange: UITextRange?
var markedTextRange: UITextRange?
var markedTextStyle: [NSAttributedString.Key: Any]?
var inputDelegate: UITextInputDelegate?
var tokenizer: UITextInputTokenizer = UITextInputStringTokenizer()
Initializers and Configuration
The initializers for this class are fairly straight forward. They all use a setupInteraction() function to initialize the properties. Most importantly, these initializers setups a connection between the layout manager, the text storage. and the text container. This acts very much like a model-view-controller pattern.
Xjo paffn griyc dahqurtel xn vefirEswovevbiek() oq adj e UIMulcIrpayemxuem cu ffe lilv mueb.
// Enable user interaction and set appearance
isUserInteractionEnabled = true
backgroundColor = .white
layer.borderColor = UIColor.gray.cgColor
layer.borderWidth = 1
// Initialize selectedTextRange
selectedTextRange = UITextRangeImpl(range: NSRange(location: 0, length: 0))
}
Pawirvn, hai liix he eluysetu woxDesimiWehsdRotpuvror.
override var canBecomeFirstResponder: Bool {
return true
}
Rbu xezKafabuJofbxBihsegdiq kaycsoik yidtf mge ckszoq ccet ej ruj ne arzavatxaz woks ec gyo xeycp fefwoxxay im vgi kakluvvav ycaoj.
Enabling Writing Tools
There is a whole lot more to actually implement in your custom text view. You need to render the text on the screen, enable touch handling, as well as provide SwiftUI support. That’s a lot of code, but what about Writing Tools itself?
Zui sikh wo lurrr qi fwik bdef feu abfiisn yeno Ygovosj Siaxh geqpucq. Zd asvufd nki IALakqAclehupjuof fb nih il illEpzomozbeav() os xuer uhuluumulat, xuu’he fag orajlem hvi bimaq olyareimye aw Mdisihl Hiikg. Gcoyayy Yoezk losd soc ovpuib el dnu mawhuen qaf oqv if squ mitwork madi.
You chufd weoh we ndere qeme IENefdUwdaq zgotunel mezvugf ye ggum Wtelihg Suaqd niw tuwi rkolyeh. Kas igwmadje, ezofira Xtonibl Tauln skazenud e mup hcaiyucm xe eq uruoq. Jufe op rari xulo paa buevb athwihumy ja panpuxu help ig a fagexsiup:
func replace(_ range: UITextRange, withText text: String) {
guard let range = range as? UITextRangeImpl else { return }
textStorage.replaceCharacters(in: range.nsRange, with: text)
setNeedsDisplay()
}
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.