日常会有须要在文本款输入的时候限制字数,若是输入的时候,没有确认,还有字符处于高亮状态的话,此时若是直接取文本框的字符个数,获得的结果是包含高亮(即尚未确认的字符)的结果。 以下图示例:bash
UITextRange *textRange = [self.textField markedTextRange];
该方法返回一个文本区间,来表示高亮的范围。
@property (nullable, nonatomic, readonly) UITextRange *markedTextRange; // Nil if no marked text.
若是是nil的话,则表示该文本框没有高亮的区间,则说明文本框里的字符是已经确认的字符。此时计算的字符数就是准确的不带高亮的字符数。
示例以下:atom
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
//======================
- (void)textFieldDidChange:(NSNotification *)noti
{
UITextField *textField = (UITextField *)noti.object;
if ([textField isEqual:self.textField]) {
UITextRange *textRange = [self.textField markedTextRange];
if (!textRange) {//当为nil的时候来计算和截取输入的字符
if (self.textField.text.length > 10) {
self.textField.text = [self.textField.text substringToIndex:10];
}
}
}
}
复制代码
以上只是关于文本框输入的一个点儿,若有更好的方案,欢迎留言沟通。spa