1

I tried - How to disable/enable the return key in a UITextField? but this gives compilation error.

Requirement : Return key should be disabled until user enters 9 characters.

I tried textfield.enablesReturnKeyAutomatically = YES; Using this return key was disabled when no input text is available in text field.As soon as i enter text its becoming enable.

Is there any solution which works for this?

Community
  • 1
  • 1
Richa Srivastava
  • 482
  • 1
  • 7
  • 24
  • "but this gives compilation error" which one? – Larme Jan 11 '17 at 10:03
  • Don't think it's possible doing this _legally_. Might be worth checking this out: http://stackoverflow.com/questions/788323/how-to-disable-enable-the-return-key-in-a-uitextfield – Ramon Jan 11 '17 at 10:04
  • 3
    You can't do this, better use `textFieldShouldReturn` method and throw error if your condition not met, allow to return if it meets. – iphonic Jan 11 '17 at 10:07

3 Answers3

1

please select "Auto Enable Return key"

enter image description here

Try this one its work for me

- (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);
}
Birendra
  • 623
  • 1
  • 5
  • 17
  • 1
    This only disable return key when there is no value in textfield, as soon as you enter a char in textfield the return key gets enabled, i want it to be disabled until 9 chars. – Richa Srivastava Jan 11 '17 at 10:41
1

You cannot disable returnKey with text in the UITextField. As specified in Apple Doc

If you set it to YES, the keyboard disables the Return key when the text entry area contains no text.

For the behaviour you want to achieve, you can block the code that will be executed on click on returnKey

Conform your class to UITextFieldDelegate

Set the

textfield.delegate = self

Implement the protocol method

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if( textField.text.length < 9)
    {
        return NO;
    }
    return YES;
}
Anoop Nyati
  • 339
  • 2
  • 11
0

You can use UITextFieldDelegate method to find 9 characters, and enable key that time until disable it. show the code below: I have written this code in swift you can write in 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
}
Sagar Chauhan
  • 5,715
  • 2
  • 22
  • 56