控制TextField的内容长度

参考如下代码(下例是控制设置交易密码,控制6位):

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)textFieldDidChange:(NSNotification *)notification
{
    UITextField *textField = (UITextField *)notification.object;
    
    if ( textField.text.length > 6 && textField == _oldTransactionPasswordTextField)
    {
        _oldTransactionPasswordTextField.text = [textField.text substringToIndex:6];
    }
    
    if ( textField.text.length > 6 && textField == _transPasswordTextField)
    {
        _transPasswordTextField.text = [textField.text substringToIndex:6];
    }
}

采用通知做法比delegate中

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string这个方法要好一些(个人觉得)

 

posted @ 2016-10-11 17:59  ~道一~  阅读(683)  评论(0编辑  收藏  举报