iOS textView光标位置输入以及删除字符或者emoji表情(自定义键盘的删除方法)


/**

 *  光标位置输入

 *

 *  @param emoji 要输入的内容emoji和字符

 */

- (void)insertStringWithGuangBiaotext:(UITextView *)textView emoji:(NSString *)emoji {

    NSRange range = textView.selectedRange;

    NSLog(@"%zd-光标位置输入-%zd",range.length,range.location);

    NSUInteger location  = textView.selectedRange.location;

    NSString * textStr = textView.text;

    NSString *resultStr = [NSString stringWithFormat:@"%@%@%@",[textStr substringToIndex:location],emoji,[textStr substringFromIndex:location]];

    textView.text = resultStr;

    range.location = range.location + [emoji length];

    NSLog(@"%zd=%zd+%zd",range.location,range.location,[emoji length]);

    textView.selectedRange = NSMakeRange(range.location,0);

}

/**

 *  光标位置删除

 */

- (void)deleteString:(UITextView *)textView {

    NSRange range = textView.selectedRange;

    NSLog(@"%zd-表情删除-%zd",range.length,range.location);

    if (textView.text.length > 0) {

        NSUInteger location  = textView.selectedRange.location;

        NSString *head = [textView.text substringToIndex:location];

        if (range.length ==0) {

            

        }else{

            NSLog(@"文字为全选");

            textView.text =@"";

        }

        

        if (location > 0) {

//            NSUInteger location  = self.inputView.toolBar.textView.selectedRange.location;

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

            [self lastRange:head];

            NSLog(@"%zd===%zd",[self lastRange:head].location,[self lastRange:head].length);

            NSLog(@"%@",str);

            

            [str deleteCharactersInRange:[self lastRange:head]];

            

            NSLog(@"%@",str);

            textView.text = str;

            textView.selectedRange = NSMakeRange([self lastRange:head].location,0);

            

        } else {

            textView.selectedRange = NSMakeRange(0,0);

        }

    }

}


/**

 *  计算选中的最后一个是字符还是表情所占长度

 *

 *  @param str 要计算的字符串

 *

 *  @return 返回一个 NSRange

 */

- (NSRange)lastRange:(NSString *)str {

    NSRange lastRange = [str rangeOfComposedCharacterSequenceAtIndex:str.length-1];

    return lastRange;

}


 

你可能感兴趣的:(键盘,UITextField,UITextView,输入框)