iOS:使用目标c禁用键盘中的返回键

时间:2017-01-11 10:02:31

标签: ios objective-c uitextfield

我试过了 - How to disable/enable the return key in a UITextField?但这会导致编译错误。

要求:应停用返回键,直到用户输入9个字符。

我尝试了textfield.enablesReturnKeyAutomatically = YES;当文本字段中没有输入文本时,使用此返回键被禁用。只要我输入文本,它就会变为启用。

有没有适用于此的解决方案?

3 个答案:

答案 0 :(得分:1)

请选择"自动启用返回键"

enter image description here

尝试这个为我工作

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (newString.length == 9) {

        self.txtTextField.enablesReturnKeyAutomatically = YES;

    }

    return (newString.length<=10);
}

答案 1 :(得分:1)

您无法在UITextField中禁用带有文字的returnKey。正如Apple Doc

中所述
  

如果将其设置为YES,则当文本输入区域不包含文本时,键盘将禁用Return键。

对于您想要实现的行为,您可以阻止单击returnKey时将执行的代码

使您的班级符合UITextFieldDelegate

设置

textfield.delegate = self

实施协议方法

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if( textField.text.length < 9)
    {
        return NO;
    }
    return YES;
}

答案 2 :(得分:0)

您可以使用UITextFieldDelegate方法查找9个字符,并启用该时间键直到禁用它。显示以下代码: 我在swift中编写了这段代码,你可以在Objective-C中编写

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    // Limit to 9 characters
    if range.location >= 9 {
        txtCity.enablesReturnKeyAutomatically = true
    } else { 
       txtCity.enablesReturnKeyAutomatically = false
}