iOS 11 使用两种方法替换(Method Swizzling)去掉导航栏返回按钮的文字 - IOS - 服务器之家

米米素材网

这篇文章主要介绍了iOS 11 使用方法替换(Method Swizzling)去掉导航栏返回按钮的文字,需要的朋友可以参考下

  方法一:设置barbuttonitem的文本样式为透明颜色,代码如下:

?
1
2
[[uibarbuttonitem appearance] settitletextattributes:@{nsforegroundcolorattributename: [uicolor clearcolor]} forstate:uicontrolstatenormal];
[[uibarbuttonitem appearance] settitletextattributes:@{nsforegroundcolorattributename: [uicolor clearcolor]} forstate:uicontrolstatehighlighted];

   此外这种方法会导致title不能居中,被偏移很多,如下所示(虽然不被显示,也占了导航栏左边很大一部分位置)

iOS 11 使用两种方法替换(Method Swizzling)去掉导航栏返回按钮的文字

     方法二:给uiviewcontroller添加类别,然后在load方法里面用method swzilling方法替换 交换viewdidappear,部分代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
+(void)load {
  swizzlemethod([self class], @selector(viewdidappear:), @selector(ac_viewdidappear));
}
- (void)ac_viewdidappear{
  self.navigationitem.backbarbuttonitem = [[uibarbuttonitem alloc]
                       initwithtitle:@""
                       style:uibarbuttonitemstyleplain
                       target:self
                       action:nil];
  [self ac_viewdidappear];
}
void swizzlemethod(class class, sel originalselector, sel swizzledselector)
{
  // the method might not exist in the class, but in its superclass
  method originalmethod = class_getinstancemethod(class, originalselector);
  method swizzledmethod = class_getinstancemethod(class, swizzledselector);
  // class_addmethod will fail if original method already exists
  bool didaddmethod = class_addmethod(class, originalselector, method_getimplementation(swizzledmethod), method_gettypeencoding(swizzledmethod));
  // the method doesn't exist and we just added one
  if (didaddmethod) {
    class_replacemethod(class, swizzledselector, method_getimplementation(originalmethod), method_gettypeencoding(originalmethod));
  }
  else {
    method_exchangeimplementations(originalmethod, swizzledmethod);
  }
}

注意事项:

要给整个backbuttonitem赋值才可以,这种方法不行,因为backbarbuttonitem默认为空,给nil方法消息,默认声明都不执行(参考官网

self.navigationitem.backbarbuttonitem.title = @" ";

leftbarbuttonitem 与backbarbuttonitem 的显示关系:

有leftbarbuttonitem则优先显示当前vc的leftbarbuttonitem,无则显示上个vc的backbarbuttonitem,再无则显示上个vc的title(参考官网   还是官网解释的清楚)

iOS 11 使用两种方法替换(Method Swizzling)去掉导航栏返回按钮的文字

总结

以上所述是小编给大家介绍的ios 11 使用两种方法替换(method swizzling)去掉导航栏返回按钮的文字,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对米米素材网网站的支持!

原文链接:https://www.cnblogs.com/Apple2U/archive/2018/05/04/8991662.html