2

如何为导航栏上的 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];
}
4

2 回答 2

11

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

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem     *)item
{
  //insert your back button handling logic here
  // let the pop happen
  return YES;
}     
于 2012-01-12T20:06:58.830 回答
3

这听起来像是一份工作UIAlertView。而不是在你的方法中调用 popViewControllerAnimated: IBActionalloc/init aUIAlertView并呈现它。然后,当用户点击 上的按钮时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:)];
于 2010-11-17T18:34:23.347 回答