Objective C how to get the numeric value of a UITextPosition

3.6k Views Asked by At

I need to get the numeric value of the start and end of a UIText range. So far I can only print out the description as a string.

From looking at the selectedTextRange, I take it that it is maybe a struct? How do I get an element of a struct?

UITextRange *selectedRange = [myTextView selectedTextRange];

NSLog(@"selectedRange.start %@, selectedRange.end %@ ", selectedRange.start.description, selectedRange.end.description);

Here is the description:

2013-03-26 13:44:03.127 AttributedString[24678:907] selectedRange.start <UITextPosition: 0x1ead8f10, 8, {"Rrrttgh "}, {"gggggh ggg..."}>, selectedRange.end <UITextPosition: 0x1eaf7860, 14, {"...tgh gggggh"}, {" gggg"}> 
2

There are 2 best solutions below

0
On BEST ANSWER

There is an answer to a similar question here: UITextPosition to NSRange.

Basically you call -offsetFromPosition:toPosition: on the UITextRange's start and end, with an initial position of myTextView.beginningOfDocument.

0
On

A UITextView conforms to UITextInput. As part of this protocol it must implement with, and process, its own subclasses of UITextRange and UITextPosition. These are not structs, but objects.

You can get a simple numeric position by using offSetFromPosition:toPosition: and passing in beginningOfDocument to get the start position. All of these methods will be implemented by UITextView. You can also pass in the start and end of the range to find out the length of a selection.

Full protocol reference here.