2016-09-02 13 views
9

Giả sử, tôi có một chuỗi trong một UITextView đó là:iOS loại bỏ từ từ UITextView

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

Khi tôi gõ vào văn bản, tôi có thể xóa từng ký tự. Nhưng những gì tôi muốn là nếu bất kỳ từ nào bắt đầu bằng @ (như: @are) thì khi tôi nhấn vào từ đó và nhấn backspace toàn bộ từ (nghĩa là @are) sẽ bị xóa thay vì ký tự. Có thể là khi tôi gõ vào bất kỳ từ nào có tiền tố '@' (như: @are) nó sẽ được đánh dấu và nhấn backspace sẽ xóa từ đó?

Tôi có thể làm như thế nào?

+0

thử điều này: http://stackoverflow.com/q/28822467/2603230 – Arefly

+0

câu hỏi là tốt .. –

+0

Bạn sẽ sử dụng các lựa chọn mặc định cửa sổ bật lên hoặc làm programatically? –

Trả lời

5

enter image description here

Ok tôi có giải pháp cho điều đó và làm việc :)

- (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 
+0

xin vui lòng chấp nhận câu trả lời của tôi nếu nó giúp như vậy khác có thể có được lợi thế nếu trong cùng một vấn đề –

+0

chấp nhận câu trả lời của bạn. –

0

Đặt delegate của UITextView. Thực hiện các phương pháp đại biểu như sau: -

- (BOOL)textView:(UITextView *)textView 
shouldChangeTextInRange:(NSRange)range 
replacementText:(NSString *)text{ 

    if([text isEqualToString:@""]){//means user pressed backspace 
     NSArray *arrayOfWords = [textView.text componentsSeparatedByString:@" "];// Separate all the words separated by space 
     NSString *lastWord = [arrayOfWords lastObject];// Get the last word (as we are working with backspace) 

     if([lastWord hasPrefix:@"@"]){ 
      textView.text = [textView.text stringByReplacingOccurrencesOfString:lastWord withString:@" "];//if last word starts with @, then replace it with space 
     } 
    } 

    return YES; 
}