處理兩種情況
非根控制器展示出來(lái)怪蔑,可能有兩種情況:
modal出來(lái)的
另一種是push
控制器的2個(gè)只讀屬性:`presentedViewController` 和 `presentingViewController`
通過(guò)`當(dāng)前顯示控制器`的`presentingViewController屬性`來(lái)判斷屬于哪種情況:
如果是`nil`贮配,表示是UINavigationController對(duì)象`push`過(guò)來(lái)的,否則是modal過(guò)來(lái)的
`[A presentViewController:B animated:YES completion:nil];`
`A.presentedViewController —> B;`
`B.presentingViewController —> A;`
有 正在把`我`舉起來(lái)的人
> presentedViewController是顯示出來(lái)的控制器
使用說(shuō)明
- 控制器繼承
MGBaseViewController
即可 - 首頁(yè)的leftBarButtonItem不用設(shè)置
- 不用設(shè)置push控制器和modal出來(lái)控制器的leftBarButtonItem
- 有的控制器返回按鈕不是pop,而是要dismiss(present推進(jìn)去的)
- 統(tǒng)一處理2種情況的返回
@interface MGBaseViewController ()
@end
@implementation MGBaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupBackBarButtonItem];
}
/**
創(chuàng)建返回按鈕
1. modal出來(lái)的
2. push進(jìn)來(lái)的
*/
- (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出來(lái)的控制器
// 返回是diss
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
} else { // push進(jìn)來(lái)的
// 返回是pop
[self.navigationController popViewControllerAnimated:YES];
}
}
@end
完整版點(diǎn)擊返回按鈕
-(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];
}
}
}