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];
    }
    
}

 

posted on 2015-12-28 22:19  森code  阅读(1277)  评论(0编辑  收藏  举报