2

如何將動作設置爲導航欄上的backButtonItem?我有一個導航欄,當我按下後退按鈕時,我需要向用戶發送一條消息,並且只有在用戶的反應後才返回到前一個視圖。我該怎麼做?感謝名單!如何將動作設置爲導航欄上的backButtonItem?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    //no one field don't changed yet 
    isDirty = FALSE; 

    //edited user 
    //set default values 
    newData = [data copy]; 

    //setting navigation controller rigth button 
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" 
                   style:UIBarButtonSystemItemDone 
                    target: self 
                    action: @selector(saveBtnUserClick)]; 
    self.navigationItem.rightBarButtonItem = rightButton; 
    [rightButton release]; 


    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" 
                    style:UIBarButtonSystemItemDone 
                    target: self 
                    action: @selector(backBtnUserClick)]; 

    self.navigationItem.backBarButtonItem = leftButton; 
    [leftButton release]; 
} 

//我的反應

-(IBAction) backBtnUserClick 
{ 
    NSLog(@"\n Back pressed"); 

    //back to previous view 
    [self.navigationController popViewControllerAnimated: TRUE]; 
} 

回答

2

這聽起來像UIAlertView工作方法。而不是調用popViewControllerAnimated:在你的IBAction方法中,alloc/init a UIAlertView並呈現它。然後,當用戶點擊UIAlertView上的按鈕時,請關閉UIAlertView並致電popViewControllerAnimated:

- (IBAction)backBtnUserClicked:(id)object { 
    UIAlertView *av = [[[UIAlertView alloc] initWithMessage:@"Wait!" 
      delegate:self 
       cancelButtonTitle:@"Ok" 
       otherButtonTitles:nil] autorelease]; 
    [av show]; 
} 

在您的UIAlertViewDelegate方法調用popViewControllerAnimated:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    [[self navigationController] popViewControllerAnimated:YES]; 
} 

設置在背面按鈕的動作:

[[[self navigationController] leftBarButtonItem] setTarget:self]; 
[[[self navigationController] leftBarButtonItem] setAction:@selector(backBtnUserClicked:)]; 
+0

感謝名單用這個!但!!如何設置導航控制返回按鈕的方法。我做不到。 – yozhik 2010-11-18 01:00:44

+0

看到我上面的編輯。 – 2010-11-18 15:14:10

11

添加< UINavigationControllerDelegate>在頭文件和.M

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem  *)item 
{ 
    //insert your back button handling logic here 
    // let the pop happen 
    return YES; 
}  
+4

這應該是'UINavigationBarDelegate'嗎? – Chris 2014-03-11 16:51:12

+0

這是shouldPopItem的正確實現,所有其他方式都有問題。 http://www.hkwebentrepreneurs.com/2013/11/ios-prevent-back-button-navigating-to.html – 2016-01-26 17:54:09

相關問題