Question

I used a string array for emoticons like this:

NSArray *emoticons = @[@"[smile]",@"[cry]",@"[happy]" ...]

then in a UITextView displaying a string like this:

I'm so happy now [happy] now [smile]

When I click a backward or delete button, if the last word is in emoticons, I want a whole emoticon string be deleted, not the last one character only.

Any idea?

Was it helpful?

Solution

Try this,

NSString *string = self.textView.text;
__block NSString *deleteWord = nil;
__block NSRange rangeOfWord;

[string enumerateSubstringsInRange:NSMakeRange(0, self.textView.selectedRange.location + self.textView.selectedRange.length) options:NSStringEnumerationByWords | NSStringEnumerationReverse usingBlock:^(NSString *substring, NSRange subrange, NSRange enclosingRange, BOOL *stop) {
    deleteWord = substring;
    rangeOfWord = enclosingRange;
    *stop = YES;
}];


if ([emoticons containsObject:deleteWord]) {
    string = [string stringByReplacingCharactersInRange:rangeOfWord withString:@""];
    self.textView.text = string;
    self.textView.selectedRange = NSMakeRange(rangeOfWord.location, 0);
}

OTHER TIPS

You might achieve something like this with the UITextViewDelegate method textView:shouldChangeTextInRange:replacementText: checking what is about to be deleted and remove the whole [emoticon] word.

I am giving you the idea that i used.

as you do not mentioned what you used as emoticons.
but for delete logic i think you will get idea from my this code.

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

    NSString *lastChar = [txthiddenTextField.text substringFromIndex: [txthiddenTextField.text length] - 1];
    NSLog(@"Last char:%@",lastChar);
    txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];

    NSString *strPlaceHolder;
    strPlaceHolder = txthiddenTextField.text;

    if([lastChar isEqualToString:@"]"])
    {
        int j = 1;
        for (int i = [txthiddenTextField.text length]-1; i >=0; --i)
        {



            NSString *lastChar = [txthiddenTextField.text substringFromIndex: [txthiddenTextField.text length] - 1];
            if([lastChar isEqualToString:@"["])
            {
                NSLog(@"%d",j);
                txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];
                // NSLog(@"Processing character %@",strPlaceHolder);
                break;
            }
            txthiddenTextField.text = [txthiddenTextField.text substringToIndex:[txthiddenTextField.text length] - 1];
            j = j+1;


        }
    }

    NSLog(@"My text fild value :%@",txthiddenTextField.text);

    return YES;
}

So, from here you have to check if the closing bracket is coming or not.
if closing bracket will come then up to opening bracket you have to delete.

then whole emoticon will delete.

hope this helps....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top