封装导航栏及返回,获取控件所在控制器 iOS

来源:互联网 发布:浙江省儿童dna数据库 编辑:程序博客网 时间:2024/05/01 01:22

当一个项目发现每个返回的按钮都是一样的,并且标题的字体也不是系统的字体,如果每个页面都去设置返回按钮,重新设置标题字体,这样代码看着繁杂,而且会浪费很多时间,这时候就有必要封装一下了。。。

首先返回按钮,需要在当前页面pop 到上一个页面的话,有两种方式:一 写一个点击代理,在用到的页面实现它,二 就是获取button所在的当前控制器,然后pop出去。 但是第一个方法,还需要到用到的页面去实现代理,也比较麻烦,那就来说第二种

首先获取当前控制器的方法:

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

获取完之后,我们就使用这个来封装自己的简单的导航栏,示例代码:

+ (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;        }    }}
阅读全文
0 0
原创粉丝点击