Reputation: 2890
What I have now?
I have two view controllers (VCA & VCB) and a navigation controller. VCA can push to VCB and VCB can go back to VCA by pressing back button in the navigation bar of VCB.
What I want to do?
I want to add another button in VCB to do the same thing as the back button in navigation bar does, that is when that button is pressed, I should be lead back to VCA, how can I do it?
What I have tried?
I tried to add a button in VCB and controller drag a line from the button to VCA so that they are connected, but I found that VCA's viewDidLoad
method is called each time I back from VCB, this is not what I wanted.
Thanks!
Upvotes: 0
Views: 72
Reputation: 788
You can realize some button (object of UIButton class), for example like this:
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
backButton.frame = CGRectMake(60.0f, 40.0f, 200.0f, 50.0f);
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:28.0f];
backButton.titleLabel.shadowOffset = CGSizeMake (0.0f, 1.0f);
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[backButton setTitleShadowColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backButton];
And also you must to define corresponding selector for action of the button:
- (void)goBack {
[self.navigationController popViewControllerAnimated:YES];
}
Now, if you click this button you will come to previous view controller.
Upvotes: 1
Reputation: 8772
The action that is fired when you press a back button to pop a ViewController is:
popViewControllerAnimated:(BOOL)animated
So what you can do it to create a button and add that action to it:
UIButton *goBackButton = [[UIButton alloc] initWithFrame:CGRectMake(0,64,50,50)];
[goBackButton addTarget:self action:@selector(goBackAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:goBackButton];
Now you actually have to implement that goBackAction:
-(IBAction)goBackAction:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
You could actually add the popViewControllerAnimated action to the button, like:
[goBackButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
The problem is that you are not able to pass that animated parameter to the method which will result in it using some junk that happens to be where that parameter was expected to be in memory. The result will be the pop sometimes being animated and other times not.
Upvotes: 1