UITextField 限制長度
阿新 • • 發佈:2018-11-28
static int MaxLength = 16; - (void)viewDidLoad { [super viewDidLoad]; [self.myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; } - (void)textFieldDidChange:(UITextField *)textField{ //輸入中文,即textField.textInputMode.primaryLanguage為:zh-Hans(簡體)、zh-Hant(繁體)的時候,如果有佔位拼音就退出,不做計算 if (textField.markedTextRange != nil) { return; }
NSString *tempString = textField.text;
// 去掉首尾的空格和回車 // tempString = [tempString stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
if (tempString.length > MaxLength) { tempString= [tempString substringToIndex:MaxLength]; } textField.text = tempString; } - (void)dealloc { [NSNotificationCenter.defaultCenter removeObserver:self]; }