UITextField限制输入的字符个数。比如输入手机号时,只能是11位

- (void)setupTextField
{
    UITextField *tf = [[UITextField alloc] init];
    
    tf.keyboardType = UIKeyboardTypeNumberPad;
    
    tf.frame = CGRectMake(80, 80, 200, 40);
    
    tf.backgroundColor = [UIColor redColor];
    
    [self.view addSubview:tf];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textfieldEditChange:) name:@"UITextFieldTextDidChangeNotification" object:tf];
}

- (void)textfieldEditChange:(NSNotification *)noti
{
    UITextField *textField = noti.object;
    
    if (textField.text.length > 11)
    {
        textField.text = [textField.text substringToIndex:11];
    }
    
}
原文地址:https://www.cnblogs.com/fs-ios/p/5084217.html