Instruction 02

In addition to requesting how Writing Tools looks on a view and the kind of output it sends back, you can do a couple more sophisticated kinds of configuration:

  • Setting a protected range of text that Writing Tools should not attempt to change.
  • Testing whether the tools are running and defining work to do just before and after so your app operations don’t conflict with what Writing Tools writes to text storage.

Defining Ignored Text Ranges

Although Writing Tools offers useful suggestions, there will be times when the user expects their text to remain exactly as entered, like in code blocks or quotes.

To achieve this, you’ll use the writingToolsIgnoredRangesIn delegate method.

func textView(_ textView: UITextView, writingToolsIgnoredRangesIn enclosingRange: 
  NSRange) -> [NSRange] {
    let text = textView.textStorage.attributedSubstring(from: enclosingRange)
    return rangesInappropriateForWritingTools(in: text)
}

This method lets you define specific ranges of text that should remain untouched.

It takes a textView and an enclosingRange, which is of type NSRange. enclosingRange specifies a range of text in the UITextView. The method returns an array of NSRange objects indicating the parts of the text that Writing Tools should ignore.

Note: normally, without any ignored ranges set, Writing Tools may extend the text it considers beyond the user’s selection to sentence boundaries or further to give its model more context.

Preventing Unexpected Data Loss or Changes

Next, let’s look at how to handle the app’s state when Writing Tools are active. Writing Tools can directly modify the text storage of your text view. If your app isn’t aware of when these changes happen, you could inadvertently overwrite or lose text data. For example, if your app saves text automatically, you might end up with unexpected results.

Apple provides a new Boolean and two new delegate methods for this purpose:

  • isWritingToolsActive: Boolean property on UITextView that is true while Writing Tools is interacting with the view.
  • textViewWritingToolsWillBegin(_ textView: UITextView): Delegate method for performing actions before the tools begin their work, which can alter text storage.
  • textViewWritingToolsDidEnd(_ textView: UITextView): Delegate method for restoring state after the tools have finished.
See forum comments
Download course materials from Github
Previous: Demo 01 Next: Demo 02