[英]iOS UiTextField Limit input and keyboard closing
Hi i have created a UITextField and i'm wanting to restrict it to just 3 letters. 嗨,我已经创建了一个UITextField,我想将其限制为仅3个字母。 and if its empty disable a button if not enable a button.
如果为空,则禁用按钮;否则,禁用按钮。 does anyone know how to do this?
有谁知道如何做到这一点?
i've given it a go but it's not really working properly if i type 3 letters it shows 3 but wont close the keyboard.i can't help but feel theres a better way to do this. 我已经试过了,但是如果我输入3个字母,它显示3,但不会合上键盘,它就不能真正正常工作。我不禁感到有更好的方法可以做到这一点。
heres what i've done 这是我所做的
- (void)hideKeyboardAction {
NSLog(@"Hide");
if([self.playerName length] >= 4){
[self.nameTextField resignFirstResponder];
} else if([self.playerName length] < 3) {
[self.addToScores setEnabled:FALSE];
}
}
- (IBAction)hideKeyboard:(id)sender {
[self hideKeyboardAction];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
self.playerName = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([self.playerName length] <4 ){
[self hideKeyboardAction];
}
if([self.playerName length] > 3){
[self.addToScores setEnabled:FALSE];
}
BOOL shouldStayOpen = !([self.playerName length] > 3);
return shouldStayOpen;
}
You should not replace the text in textField:shouldChangeCharactersInRange:replacementString:. 您不应替换textField:shouldChangeCharactersInRange:replacementString:中的文本。 You should check the length of the text in textField, compare the length of the range and that of the replacementString and decide (return YES/NO) whether to replace or not.
您应该检查textField中文本的长度,比较范围的长度和replaceString的长度,然后决定(返回YES / NO)是否替换。 You can also enable/disable the button in this method, based on the calculated length of the text after replacement.
您还可以根据替换后计算出的文本长度,以这种方法启用/禁用按钮。
And there is no need to hide the keyboard, in my opinion. 我认为,无需隐藏键盘。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.