简体   繁体   中英

UITextView remove last entered text

I have a UITextView being passed text by several different UITextFields on IBAction .

textView.text = [NSMutableString stringWithFormat:@"%@ %@",
textView.text,textField1.text]; 

I'm trying to remove the selected text from the TextView

textField.text = [NSMutableString stringWithString:@""];

But it removes all of the text instead of just the selected.

Could someone give me some direction on this please and thanks.

From Apple Docs:

@property(nonatomic) NSRange selectedRange

In iOS 2.2 and earlier, the length of the selection range is always 0, indicating that the selection is actually an insertion point. In iOS 3.0 and later, the length of the selection range may be non-zero.

So I suppose you should do something like this:

if (textField.selectedRange.location != NSNotFound && textField.selectedRange.length > 0)
    textField.text = [textField.text stringByReplacingCharactersInRange:textField.selectedRange withString:@""];

You can store your last entered text (eg theLastEnteredText ), then delete it from a mutable string object (eg theContent ) and set it to your textField:

[theContent deleteCharactersInRange:NSRangeFromString(theLastEnteredText)];
textField.text = theContent;

EDIT:

In case there's a same text content exists before last one, you'll delete it by mistake. So here's a better way to do so:

// .location: theContentLength - theLastEnteredTextLength
// .lenght: theLastEnteredTextLength
NSRange range = {theContentLength - theLastEnteredTextLength, theLastEnteredTextLength};
[theContent deleteCharactersInRange:range];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM