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

首先返回按钮,需要在当前页面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;
 }
 }
}

以上这篇iOS 封装导航栏及返回,获取控件所在控制器的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持悠悠之家。

点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部