Enabling an uibarbuttonitem when at least one char is written in a uitextfield

Discussion in 'iOS Programming' started by franium, Feb 25, 2011.

  1. franium macrumors member

    Joined:
    Nov 18, 2010
    #1
    Hi,

    I would to enable the done button on the navbar (in a modal view) when the user write at least a char in a uitextfield. Using textFieldDidEndEditing: enables the button when the previous uitextfield resigns first responder (so with the zero chars in the current uitextfield). textFieldShouldBeginEditing: is called when the textfield becomes the first responder.
    The solution could be
    Code:
    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    
    but neither
    Code:
     [self.navigationItem.rightBarButtonItem setEnabled:YES];
    
    or
    Code:
    [doneButton setEnabled:YES]; //doneButton is an IBOutlet tied to my Done UIBarButtonItem in IB
    
    work.
    Any ideas?
    Thanks,

    Fran
     
  2. forum user macrumors regular

    Joined:
    Aug 28, 2008
    #2
    delegates are setup for the navbar and the button?

    - Olaf
     
  3. franium thread starter macrumors member

    Joined:
    Nov 18, 2010
    #3
    It's strange... I've added a property for doneButton (and synthesize) and it worked, then I remove the property, coming back to the old code and it works also so. But now I've another problem. This code:
    Code:
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    	if (textField == password) {
    		if (textField.text.length > 0) {
    			doneButton.enabled = YES;
    		} else {
    			doneButton.enabled = NO;
    		}
    	}
    	return YES;
    }
    
    enables the button when the text length is >0, but it disables the button when the chars are 0 and 2.
    I don't understand this behaviour.
     
  4. franium thread starter macrumors member

    Joined:
    Nov 18, 2010
    #4
    I resolved with this check
    Code:
    if (textField.text.length >= 0) {
    			doneButton.enabled = YES;
    		} 
    		if (string.length == 0 && textField.text.length == 1) {
    			doneButton.enabled = NO;
    		}
    
     
  5. ulbador macrumors 68000

    ulbador

    Joined:
    Feb 11, 2010
    #5
    This!

    The prior code wasn't working because you didn't set the delegate for your nav bar to your class. By manually connecting your button to an outlet, you basically bypassed this (badly)
     
  6. franium thread starter macrumors member

    Joined:
    Nov 18, 2010
    #6
    Oh... thanks... now I've understood
     

Share This Page