Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

objective c - iOS remove word from UITextView

Suppose, I have a string in a UITextView that is :

NSString *str = @"Hello world. What @are you @doing ?" 

When I tap on the text, I can delete the character by character. But what I want is if any word starts with @ (like: @are) then when I tap on that word and press backspace the entire word (i.e, @are)should be deleted instead of a character. Is it possible that when I tap on any word that has a prefix '@' (like: @are) it will be highlighted and press backspace will delete that word ?

How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

enter image description here

Ok i have solution for that and Working :)

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

if ([string isEqualToString:@""]) {

    UITextRange* selectedRange = [textField selectedTextRange];
    NSInteger cursorOffset = [textField offsetFromPosition:0 toPosition:selectedRange.start];
    NSString* text = textField.text;
    NSString* substring = [text substringToIndex:cursorOffset];
    NSString* lastWord = [[substring componentsSeparatedByString:@" "] lastObject];

    if ([lastWord hasPrefix:@"@"]) {
        // Delete word

        textField.text =  [[self.textField text] stringByReplacingOccurrencesOfString:lastWord withString:@""];
        return NO;
    }
}
return YES;
}// return 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...