调用textFieldShouldReturn时的popViewController?

时间:2011-09-23 05:39:32

标签: iphone objective-c uinavigationcontroller uitextfield

我有一个带UINavigationController的简单UIViewController。视图控制器包含的所有内容都是单个UITextField。该视图有两个目的:

  • 创建一个新项目。在这种情况下,UINavigationController中有“取消”和“保存”按钮。
  • 编辑现有项目的名称。在这种情况下,左上角只有“后退”按钮。

我想要的是iPhone键盘上的Return键可以关闭UITextField。

这是我的textFieldShouldReturn代码:

-(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 个答案:

答案 0 :(得分:0)

好吧,我建议您使用UIButton,因为操作正在依赖,您希望在最后管理它。

    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. 
    }