Search code examples
iphonecocoa-touchiphone-sdk-3.0ios4iphone-sdk-3.2

How to disable a 'Done' button from nav bar when keyboard slides in?


I believe I can't disable it because I can't access that UIBarButttonItem programmatically
(with either viewWithTag or rightBarButtonItem).

Any suggestions (short from adding the interface without IB)?
As a test, I also tried adding a button programmatically (on the left of the nav bar), but it did not display in the nav bar.

RELEVANT CODE (In MyEditorViewControler.m):

    - (void)textFieldDidBeginEditing:(UITextField *)sender { //successfully executes when keyboard slides in

        UINavigationItem *item = self.navigationItem; //item  = 0x6420e0  OK.  (value at debugger breakpoints)
        UIBarButtonItem *doneButton4    = (UIBarButtonItem *) [self.view viewWithTag:44]; //doneButton4 = 0x0,  not OK.
        doneButton4.enabled = NO; 
    }
    - (void)textFieldDidEndEditing:(UITextField *)sender {  //successfully executes when keyboard  slides out.  
        ...
        UIButton* doneButton = (UIButton *)[self.view viewWithTag:44]; //Attempt to re-enable button.
        doneButton.enabled = YES;
    }
    - (void)viewDidLoad {   //Attempt to programmatically add a *left* button to the nav bar. Result: Button does not display in nav bar.
        .... 
        UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)];
        self.navigationItem.leftBarButtonItem = leftBarButtonItem;
        [leftBarButtonItem release];
    }

DETAILS
I would think this is a common case because that Done button:
a) is a UIBarButttonItem added from IB Library to navigation bar that is in a Scroll View that has some UITextField's.
b) behaves as expected (to save the user-entered data etc),
except for not getting disabled when keyboard appears.
c) IB > Inspector > Bar Button Item Attributes shows:
Identifier = Done
Tag = 44
Class = UIBarButtonItem


Solution

  • You can listen to a notification (UIKeyboardWillShowNotification) posted when the keyboard slides in:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    

    Then implement -keyboardWillShow:.

    -(void)keyboardWillShow {
        UIButton *button = self.navigationItem.leftBarButtonItem;
        button.enabled = NO;
    }
    

    To reenable the button again, do the same for the UIKeyboardDidHideNotification