關於iOS的文本框有時須要限制字數,如手機號,在UITextField的代理單純寫一個判斷,在字數超過限制時,這時再想刪除就刪除不掉,能夠在代理這樣寫,就解決git
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (!string.length) { return YES; } if (textField.keyboardType == UIKeyboardTypeNumberPad) { if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) { return NO; } } NSString *updatedText = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (updatedText.length > 11) // 4 was chosen for SSN verification { if (string.length > 1) { // BasicAlert(@"", @"This field accepts a maximum of 4 characters."); } return NO; } return YES; }