0
votes

I've got a simple UIViewController with a UINavigationController. All that the view controller contains is a single UITextField. This view has two purposes:

  • Create a new item. In this case, there are "Cancel" and "Save" buttons in the UINavigationController.
  • Edit the name of an existing item. In this case, there's just the "Back" button in the top-left corner.

What I'd like is for the Return key on the iPhone keyboard to dismiss the UITextField.

Here's my textFieldShouldReturn code:

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(self.navigationItem.rightBarButtonItem) {
        //If we're creating a new item (there'd be a Save button in the top right)   
        [self saveItem]; //This method just saves the Core Data for this item.
        [self.delegate addItemViewController:self didAddItem:item]; //This works fine; this method just tells the delegate to dismiss this view controller. 
    }else {
        //If there's no button in the top-right corner, then we're editing an existing fridge.
        [self saveItem]; //This method just saves the Core Data for this item.
        [self.navigationController popViewControllerAnimated:YES]; //This is what doesn't work.
    }
    [textField resignFirstResponder];
    return YES;
}
1
Cancel and Save, are they UIButtons? - alloc_iNit
try like this[textField resignFirstResponder]; [self.navigationController popViewControllerAnimated:YES]; - Srinivas
@iApple they are UIBarButtonItems, and that part of the code is working just fine. The if-statement is working great. - bryanjclark
@IdontKnowobjectivec that didn't help. Thanks though. - bryanjclark
Did you hook up your UITextField's delegate to your file owner? Also, are you sure your UINavigationController is hooked up correctly? You may also want to try calling [textField resignFirstResponder]; before the if, and putting an NSTimer on your popViewControllerAnimated call, just to make sure the UITextField has enough time to resign. - msgambel

1 Answers

0
votes

Well, I suggest you to go with UIButtons as the operation is being depended and you want to manage it at your end.

    btnSave = [UIButton buttonWithType:UIButtonTypeCustom];
    btnSave.frame = CGRectMake(250, 6, 61, 30);
    [btnSave setImage:[UIImage imageNamed:@"btn-save.png"] forState:UIControlStateNormal];
    btnSave.backgroundColor = [UIColor clearColor]; 
    [btnSave addTarget:self action:@selector(btnSave_clicked:) forControlEvents:UIControlEventTouchUpInside];   
    [self.navigationController.navigationBar addSubview:btnSave];

    - (IBAction)btnSave_clicked:(id)sender
    {
        //If we're creating a new item (there'd be a Save button in the top right)   
        [self saveItem]; //This method just saves the Core Data for this item.
        [self.delegate addItemViewController:self didAddItem:item]; //This works fine; this method just tells the delegate to dismiss this view controller. 
    }