UITextView selectedRange property

What is the string representation (or another object) for this property is applied?

Can we use Range(txtView.selectedRange, in: txtView.text) to get valid indices in UITextView.text?

What is the difference of UITextView.selectedRange to UITextView.SelectedTextRange?

Replies

selectedRange returns an NSRange instance, and the range location and length are meant to be used with text as NSString, which natively uses the UTF-16 encoding. This is because UITextView (and many other Text APIs) was implemented with Objective C long before the introduction of Swift.

Range(_:in:) converts an NSRange instance to a Swift range, which is based on the character (Character) index (String.Index) of the string (String). If the lower or upper bound of the input range (NSRange) locates in the middle of a composed character sequence or an extended grapheme cluster, Range(_:in:) adjusts the output range to include the whole Swift character. So if the “valid indices” you mentioned means the valid Swift character indices, the answer is yes.

selectedTextRange is a part of UITextInput. It is based on UITextRange and UITextPosition, and is typically used with other UITextInput APIs, such as beginningOfDocument, endOfDocument, and position(from:in:offset:).

UITextRange and UITextPosition are abstract classes. TextKit provides concrete implementation for them, and the implementation is based on NSString / NSAttributedString as well.

  • By "valid indices" I mean the indices that correspond the indices of characters in the start and end of selectedRange

Add a Comment