Getting Remaining Text After Selection is Cut

63 Views Asked by At

Is there a simple way of getting remaining text after selection is cut? Let me suppose that I have a textview control with "Hello, Jim" in it. If "Jim" is selected, I want to store "Hello" to a variable, " without using [textview1 cut:self]. In the following code, I can get the other part.

UITextRange *selectedTextRange = textview1.selectedTextRange;
NSUInteger location = [textview1 offsetFromPosition:textview1.beginningOfDocument toPosition:selectedTextRange.start];
NSUInteger length = [textview1 offsetFromPosition:selectedTextRange.start toPosition:selectedTextRange.end];
NSRange selectedRange = NSMakeRange(location, length);
NSString *str = [textview1.text substringWithRange:selectedRange];
NSLog(@"%@",str);

Of course, that's the other part.

Thank you for your help.

2

There are 2 best solutions below

2
On BEST ANSWER
NSString *remaining = [textview1.text stringByReplacingCharactersInRange:textview1.selectedRange withString:@""];
0
On

I think it's something like the following. (Revised)

NSMutableString *str = [NSMutableString stringWithString:@""];
if (textview1.text.length > length) {
    [str appendString:[textview1.text substringToIndex:location]];
    [str appendString:[textview1.text substringFromIndex:location + length]];
} else {
    [str appendString:@""];
}
[self setText:str];