欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-19 16:43:16
当一个项目发现每个返回的按钮都是一样的,并且标题的字体也不是系统的字体,如果每个页面都去设置返回按钮,重新设置标题字体,这样代码看着繁杂,而且会浪费很多时间,这时候就有必要...

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

首先返回按钮,需要在当前页面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 封装导航栏及返回,获取控件所在控制器的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: