2011-09-23 46 views
0

我有一個簡單的UIViewController與UINavigationController。視圖控制器包含的所有內容都是單個UITextField。此視圖有兩個目的:popViewController何時調用textFieldShouldReturn?

  • 創建一個新項目。在這種情況下,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; 
} 
+0

取消和保存,他們是UIButtons? –

+0

嘗試像這樣[textField resignFirstResponder]; [self.navigationController popViewControllerAnimated:YES]; – Srinivas

+0

@iApple它們是UIBarButtonItems,並且代碼的那部分工作正常。 if語句運行良好。 – bryanjclark

回答

0

好吧,我建議你UIButtons去作爲操作被依賴,你想在你地對其進行管理。

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

我已經有用適當的方法配置的保存按鈕。我的挑戰是讓鍵盤上的完成按鈕的行爲與保存按鈕的行爲相同。 – bryanjclark

相關問題