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

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

程序员文章站 2023-12-14 23:10:28
  方法一:设置barbuttonitem的文本样式为透明颜色,代码如下: [[uibarbuttonitem appearance] settitle...

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

[[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,部分代码如下

+(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)去掉导航栏返回按钮的文字,希望对大家有所帮助

上一篇:

下一篇: