控制TextField的内容长度

Posted ~~Sharp~~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了控制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这个方法要好一些(个人觉得)

 

以上是关于控制TextField的内容长度的主要内容,如果未能解决你的问题,请参考以下文章