0

working on a game based project.i am having a view controller as GameScreen. on the top of Gamescreen having a navigation bar with back button(default).Now if user clicks on back button i have to show alert. so how to determine "backbutton got clicked."? any suggestion? Thanks

maddy
  • 4,001
  • 8
  • 42
  • 65

3 Answers3

1

In your viewdidload method :

UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"back_button.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];

In the cancel method:

- (IBAction) cancel:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];

    or show your alert view
}

Otherwise also you can just override the method if you do not want a custom back button.

Praveen S
  • 10,355
  • 2
  • 43
  • 69
  • i am trying this in viewdidLoad:-UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@""]; [addButton action:@selector(backbuttonclicked)]; [addButton style:UIBarButtonItemStyleBordered]; and selector method as:-(IBAction)backbuttonclicked:(id)sender { NSLog(@"back button clicked"); } i have also declared method in .h file.what wrong i am doing. [addButton target:self]; [addButton release]; – maddy May 26 '11 at 10:23
  • You are not assigning the button to the navigation bar button – Praveen S May 26 '11 at 10:56
1

Your UINavigationBarDelegate has got a nice method for that, called shouldPopItem.

You can override that in your delegate and show there the alert. This gives you also a chance to cancel the going-back (popping).

sergio
  • 68,819
  • 11
  • 102
  • 123
0

Stopping the self.navigationItem.leftBarButtonItem from exiting a view - here you go maddy, answers the question in a different context but same basis -

Community
  • 1
  • 1
theiOSDude
  • 1,480
  • 2
  • 21
  • 36