处理两种情况
非根控制器展示出来,可能有两种情况:
modal出来的
另一种是push
控制器的2个只读属性:`presentedViewController` 和 `presentingViewController`
通过`当前显示控制器`的`presentingViewController属性`来判断属于哪种情况:
如果是`nil`,表示是UINavigationController对象`push`过来的,否则是modal过来的
`[A presentViewController:B animated:YES completion:nil];`
`A.presentedViewController —> B;`
`B.presentingViewController —> A;`
有 正在把`我`举起来的人
> presentedViewController是显示出来的控制器
使用说明
- 控制器继承
MGBaseViewController
即可 - 首页的leftBarButtonItem不用设置
- 不用设置push控制器和modal出来控制器的leftBarButtonItem
- 有的控制器返回按钮不是pop,而是要dismiss(present推进去的)
- 统一处理2种情况的返回
@interface MGBaseViewController ()
@end
@implementation MGBaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupBackBarButtonItem];
}
/**
创建返回按钮
1. modal出来的
2. push进来的
*/
- (void)setupBackBarButtonItem
{
// 只有根控制器不加leftBarButtonItem
if (self.presentingViewController || self.navigationController.childViewControllers.count > 1) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"navigationButtonReturn"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"navigationButtonReturnClick"] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button sizeToFit];
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.contentEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
[button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
}
- (void)buttonAction
{
if (self.presentingViewController) { // modal出来的控制器
// 返回是diss
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
} else { // push进来的
// 返回是pop
[self.navigationController popViewControllerAnimated:YES];
}
}
@end
完整版点击返回按钮
-(void)onBackButtonClick
{
[self.view endEditing:YES];
if (self.presentingViewController &&
(!self.navigationController ||self == self.navigationController.viewControllers.firstObject)) {
[self dismissViewControllerAnimated:YES completion:nil];
}
else{
if (self != self.navigationController.viewControllers.firstObject) {
[self.navigationController popViewControllerAnimated:YES];
}
}
}