溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

iOS11中如何使用兩種方法替換Method Swizzling去掉導航欄返回按鈕的文字

發(fā)布時間:2021-08-09 14:09:33 來源:億速云 閱讀:107 作者:小新 欄目:移動開發(fā)

小編給大家分享一下iOS11中如何使用兩種方法替換Method Swizzling去掉導航欄返回按鈕的文字,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

  方法一:設置BarButtonItem的文本樣式為透明顏色,代碼如下:

[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal]; 
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];

   此外這種方法會導致title不能居中,被偏移很多,如下所示(雖然不被顯示,也占了導航欄左邊很大一部分位置)

iOS11中如何使用兩種方法替換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方法消息,默認聲明都不執(zhí)行(參考官網(wǎng))

self.navigationItem.backBarButtonItem.title = @" ";

leftBarButtonItem 與backBarButtonItem 的顯示關(guān)系:

有l(wèi)eftBarButtonItem則優(yōu)先顯示當前VC的leftBarButtonItem,無則顯示上個VC的backBarButtonItem,再無則顯示上個VC的title(參考官網(wǎng)   還是官網(wǎng)解釋的清楚)

iOS11中如何使用兩種方法替換Method Swizzling去掉導航欄返回按鈕的文字

以上是“iOS11中如何使用兩種方法替換Method Swizzling去掉導航欄返回按鈕的文字”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

ios
AI