控制TextField的内容长度

时间:2023-03-08 22:57:04
控制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 > && textField == _oldTransactionPasswordTextField)
{
_oldTransactionPasswordTextField.text = [textField.text substringToIndex:];
} if ( textField.text.length > && textField == _transPasswordTextField)
{
_transPasswordTextField.text = [textField.text substringToIndex:];
}
}

采用通知做法比delegate中

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