如何在导航栏上设置对backButtonItem的操作?

时间:2010-11-17 17:19:54

标签: iphone uinavigationcontroller uinavigationbar back-button

如何在导航栏上设置对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 个答案:

答案 0 :(得分:11)

添加< UINavigationControllerDelegate>在头文件中,并在.m

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

答案 1 :(得分:2)

这听起来像是UIAlertView的工作。而不是在IBAction方法中调用popViewControllerAnimated:来分配/初始化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:)];