iOS 11 使用方法替換(Method Swizzling),去掉導覽列返回按鈕的文字

來源:互聯網
上載者:User

標籤:nbsp   ima   cto   bool   圖片   add   control   賦值   text   

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

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

 

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

 

     方法二:給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),去掉導覽列返回按鈕的文字

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.