2016-09-02 7 views
9

मान लीजिए UITextView से शब्द हटाने के लिए, मैं एक UITextView है कि में एक स्ट्रिंग है:आईओएस

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

जब मैं पाठ पर टैप करते हैं, मैं वर्ण दर वर्ण हटा सकते हैं। लेकिन मुझे क्या चाहिए यदि कोई शब्द @ (जैसे: @are) से शुरू होता है, तो जब मैं उस शब्द पर टैप करता हूं और बैकस्पेस दबाता हूं तो पूरे शब्द (i.e, @are) को किसी चरित्र के बजाय हटा दिया जाना चाहिए। क्या यह संभव है कि जब मैं किसी भी शब्द पर टैप करता हूं जिसमें '@' (जैसे: @are) है तो इसे हाइलाइट किया जाएगा और बैकस्पेस उस शब्द को हटा देगा?

मैं यह कैसे कर सकता हूं?

+0

इस प्रयास करें: http://stackoverflow.com/q/28822467/2603230 – Arefly

+0

सवाल अच्छा है .. –

+0

आप डिफ़ॉल्ट चयन पॉपअप का उपयोग किया जाएगा या प्रोग्राम के कर? –

उत्तर

5

enter image description here

ठीक है मैं के लिए है कि और कार्य समाधान :)

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

कृपया मेरे उत्तर को स्वीकार करें यदि इससे मदद मिलती है तो अन्य लाभ –

+0

आपके उत्तर को स्वीकार कर सकते हैं। –

0

सेट UITextView की delegate है। इस प्रकार प्रतिनिधि विधि को लागू करें: -

- (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; 
}