蘋果在人機交互上一直追求極致。iOS 7新增了一個不起眼卻很貼心的功能,也就是這行API:
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
它的作用是讓NavigationController堆棧中的UIViewController支持右滑手勢——不必去點右上角的返回按鈕,只需在屏幕左側輕輕一滑,界面便會返回。隨著iPhone屏幕越來越大,這個小功能無疑是手指不夠長、單手操作不便用戶的福音。
遺憾的是,當我們需要定制返回按鈕時,這個手勢往往會失效。也就是說,一旦自定義了navigationItem的leftBarButtonItem,右滑返回就不再生效。
針對這個問題,可以採用以下兩種解決方案:
1.重新設置手勢的delegate
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
2.自己接管手勢事件
[self.navigationController.interactivePopGestureRecognizer addTarget:self action:@selector(handleGesture:)];
如果只是想簡單地定制返回按鈕,第一種方式最省事,一句代碼即可搞定;若有更複雜的定制需求,則可選擇第二種自行響應手勢。
問題二:自定義返回按鈕後如何保留右滑返回
系統自帶的backBarButtonItem無需任何代碼即可實現右滑後退,但一旦為了修改樣式而自定義leftBarButtonItem,右滑便會失效。通過設置interactivePopGestureRecognizer的相關屬性即可解決。這個手勢有兩個關鍵屬性:
1. self.navigationController.interactivePopGestureRecognizer.enabled = YES | NO; //手勢是否生效
2. self.navigationController.interactivePopGestureRecognizer.delegate = self; //手勢代理,一般設為self
其中enabled在viewController中默認為YES。僅僅按第2條設置delegate後,當前界面雖能右滑返回,但當回到NavigationController的rootView再次右滑時,程序卻會出問題——再次push子控制器時會卡在當前界面無法跳轉。
一個可靠的解決方案是:假設有A、B兩個控制器,rootView為A,點擊後push出B。在A中禁用右滑手勢,在B中啟用它。代碼如下:
A的viewDidAppear中:
- (void)viewDidAppear:(BOOL)animated {
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
self.navigationController.interactivePopGestureRecognizer.enabled = NO; //rootView禁止滑動
}
}
B的viewDidLoad中:
- (void)viewDidLoad {
UIBarButtonItem * backItem = [self barButtonForImageNames:@[@"icon-返回", @"", @""] action:@selector(popBack)];
backItem.title = @"";
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
self.navigationItem.leftBarButtonItem = backItem;
}
這樣便能保證在A中右滑返回後,再次push B時不會卡在A界面。
在實際項目中,通常會建立風格統一的基礎viewController,並在其中擴展一個配置leftBarButtonItem的方法,把B的viewDidLoad裡那段代碼封裝進去。這樣創建返回按鈕的同時也一併處理了右滑返回,無需在每個viewController中重複書寫;而A的viewDidAppear方法則只需放在NavigationController的rootView中即可。