對(duì)textField或者textView做文本長(zhǎng)度輸入限制
在viewDidLoad中添加監(jiān)聽
// 限制文本輸入長(zhǎng)度
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
name:@"UITextFieldTextDidChangeNotification"
object:TextField];
#pragma mark -限制文本輸入長(zhǎng)度
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self
name:@"UITextFieldTextDidChangeNotification"
object:TextField];
}
-(void)textFiledEditChanged:(NSNotification *)obj{
UITextField *textField = (UITextField *)obj.object;
static NSInteger _textLength = 16; // 需要限制的長(zhǎng)度
NSString *toBeString = textField.text;
// 鍵盤輸入模式
NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage;
if ([lang isEqualToString:@"zh-Hans"]) { // 簡(jiǎn)體中文輸入,包括簡(jiǎn)體拼音剂买,健體五筆狐肢,簡(jiǎn)體手寫
UITextRange *selectedRange = [textField markedTextRange];
//獲取高亮部分
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 沒有高亮選擇的字添吗,則對(duì)已輸入的文字進(jìn)行字?jǐn)?shù)統(tǒng)計(jì)和限制
if (!position) {
if (toBeString.length > _textLength) {
textField.text = [toBeString substringToIndex:_textLength];
}
}
// 有高亮選擇的字符串,則暫不對(duì)文字進(jìn)行統(tǒng)計(jì)和限制
else{
}
}
// 中文輸入法以外的直接對(duì)其統(tǒng)計(jì)限制即可份名,不考慮其他語(yǔ)種情況
else{
if (toBeString.length > _textLength) {
textField.text = [toBeString substringToIndex:_textLength];
}
}
}
以上是UITextField的限制文本輸入長(zhǎng)度方法碟联,如果需要設(shè)置UITextView的文本輸入長(zhǎng)度,需把UITextField換成UITextView僵腺,把@"UITextFieldTextDidChangeNotification" 換成@"UITextViewTextDidChangeNotification"