最近在項目中發(fā)現(xiàn)原來的一些代碼的textFiled在限制字數(shù)上總是出現(xiàn)這樣或那樣的問題,今天就來整理一下幾種常用的方法.
第一種比較簡單粗暴,索然也能達到想要的結(jié)果,但是用戶體驗不太好:
-(void)textFieldDidEndEditing:(UITextField *)textField{
if (textField.text.length > 5) {
textField.text = [textField.text substringToIndex:5];
}
}
//點擊return結(jié)束編輯
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
就是在textFiled的代理方法中結(jié)束編輯時判斷一下字數(shù)長度進行截斷,比較生硬.
第二種方法是動態(tài)的判斷文本框中字數(shù),以達到判斷的目的,也是使用textFiled的代理方法
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *tostring = [textField.text stringByReplacingCharactersInRange:range withString:string];
//必須加上markedTextRange的判斷,否則在系統(tǒng)自帶的輸入法中會把未選中之前的拼音也算成字符串長度,若在搜狗輸入法上不加此判斷也沒有問題
if (textField.markedTextRange == nil) {
if (tostring.length > 5) {
textField.text = [tostring substringToIndex:5];
return NO;
}
}
return YES;
}
第三種方法使用textFiled中提供的監(jiān)聽方式UITextFieldTextDidChangeNotification:
首先在viewwillappear中設(shè)置監(jiān)聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextFiledDidChangeAction:) name:UITextFieldTextDidChangeNotification object:nil];
然后實現(xiàn)監(jiān)聽到事件時要執(zhí)行的方法
-(void)TextFiledDidChangeAction:(NSNotification *)noti{
//必須加上markedTextRange的判斷,否則在系統(tǒng)自帶的輸入法中會把未選中之前的拼音也算成字符串長度,若在搜狗輸入法上不加此判斷也沒有問題
if (_textFiled.markedTextRange == nil) {
if (_textFiled.text.length>5) {
_textFiled.text = [_textFiled.text substringToIndex:5];
}
NSLog(@"change");
}
}
但是第二種方式的話只有在不符合條件后再次觸發(fā)鍵盤才會返回NO,因此第三種方式作為合適