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

相关问题