日常會有須要在文本款輸入的時候限制字數,若是輸入的時候,沒有確認,還有字符處於高亮狀態的話,此時若是直接取文本框的字符個數,獲得的結果是包含高亮(即尚未確認的字符)的結果。 以下圖示例: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