问题描述
- 对用户输入的字符进行限制
-
有四个文本框,在用户输入时需要放入两个限制。一个是用户只能输入大写字母,并且最多只能有2个字符。代码如下:- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // Below logic is for All 4 Modifer Textfields // we are restrict the user to enter only max 2 characters in modifier textfields. if (textField==txt_modifier1 || textField==txt_modifier2 || textField==txt_modifier3 || textField==txt_modifier4) { textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseStringWithLocale:[NSLocale currentLocale]]]; NSUInteger newLength = [textField.text length] + [string length] - range.length; return (newLength > 2) ? NO : YES; } return YES; }
但是运行之后,我输入任何字符都会附加一个新字符,并且也没用成功限制2个字符的数量。
请高手指点一下,谢谢。
解决方案
注册UITextFieldTextDidChangeNotification 在这里做判断
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textChanged:)
name:UITextFieldTextDidChangeNotification
object:YOUR_TEXT_FIELD];
-(void)textChanged:(NSNotification *)notif {
//to do your logic
}
时间: 2024-10-02 23:21:24