iOS 封裝導(dǎo)航欄及返回,獲取控件所在控制器的實例
當一個項目發(fā)現(xiàn)每個返回的按鈕都是一樣的,并且標題的字體也不是系統(tǒng)的字體,如果每個頁面都去設(shè)置返回按鈕,重新設(shè)置標題字體,這樣代碼看著繁雜,而且會浪費很多時間,這時候就有必要封裝一下了。。。
首先返回按鈕,需要在當前頁面pop 到上一個頁面的話,有兩種方式:一 寫一個點擊代理,在用到的頁面實現(xiàn)它,二 就是獲取button所在的當前控制器,然后pop出去。 但是第一個方法,還需要到用到的頁面去實現(xiàn)代理,也比較麻煩,那就來說第二種
首先獲取當前控制器的方法:
UINavigationController *vc = [[UINavigationController alloc] init];
for (UIView* next = [sender superview]; next; next = next.superview) {
UIResponder* nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UINavigationController class]]) {
vc = (UINavigationController*)nextResponder;
[vc.topViewController.navigationController popViewControllerAnimated:YES];
return;
}
}
因為我這里的按鈕在navigationController上所以,這里的控制器變量都是 UINavigationController,如果需要獲取的是一般的UIViewController,那就把上面所有的UINavigationController 改成 UIViewController
獲取完之后,我們就使用這個來封裝自己的簡單的導(dǎo)航欄,示例代碼:
+ (void)setNavigationBarWithTitle:(NSString *)title controller:(UIViewController *)controller{
controller.title = title;
[controller.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName:kMainTextColor,NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Light" size:18]}];
//返回按鈕
UIButton *btn = [[UIButton alloc] init];
[btn setImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
[btn setTitleColor:kMainTextColor forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:13];
[btn addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
controller.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}
+ (void)back:(UIButton *)sender{
UINavigationController *vc = [[UINavigationController alloc] init];
for (UIView* next = [sender superview]; next; next = next.superview) {
UIResponder* nextResponder = [next nextResponder];
if ([nextResponder isKindOfClass:[UINavigationController class]]) {
vc = (UINavigationController*)nextResponder;
[vc.topViewController.navigationController popViewControllerAnimated:YES];
return;
}
}
}
以上這篇iOS 封裝導(dǎo)航欄及返回,獲取控件所在控制器的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
iOS 9 更新之Safari廣告攔截器(Content Blocker)開發(fā)教程
這篇文章主要介紹了iOS 9 更新之Safari廣告攔截器(Content Blocker)開發(fā)教程的相關(guān)資料,需要的朋友可以參考下2015-08-08
iOS在頁面銷毀時如何優(yōu)雅的cancel網(wǎng)絡(luò)請求詳解
這篇文章主要給大家介紹了關(guān)于iOS在頁面銷毀時如何優(yōu)雅的cancel網(wǎng)絡(luò)請求的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2018-05-05
Android NavigationController 右滑手勢詳解
目前蘋果手機在人機交互中盡力做到極致,在ios7中,新增了一個小小功能,用戶不用點擊右上角的返回按鈕,在屏幕左邊一滑,就會返回。下面給大家詳解Android NavigationController 右滑手勢,需要的朋友可以參考下2015-08-08

