iOS 11 使用兩種方法替換(Method Swizzling)去掉導(dǎo)航欄返回按鈕的文字
方法一:設(shè)置BarButtonItem的文本樣式為透明顏色,代碼如下:
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal]; [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];
此外這種方法會導(dǎo)致title不能居中,被偏移很多,如下所示(雖然不被顯示,也占了導(dǎo)航欄左邊很大一部分位置)
方法二:給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); } }
注意事項(xiàng):
要給整個backButtonItem賦值才可以,👇這種方法不行,因?yàn)閎ackBarButtonItem默認(rèn)為空,給nil方法消息,默認(rèn)聲明都不執(zhí)行(參考官網(wǎng))
self.navigationItem.backBarButtonItem.title = @" ";
leftBarButtonItem 與backBarButtonItem 的顯示關(guān)系:
有l(wèi)eftBarButtonItem則優(yōu)先顯示當(dāng)前VC的leftBarButtonItem,無則顯示上個VC的backBarButtonItem,再無則顯示上個VC的title(參考官網(wǎng) 還是官網(wǎng)解釋的清楚)
總結(jié)
以上所述是小編給大家介紹的iOS 11 使用兩種方法替換(Method Swizzling)去掉導(dǎo)航欄返回按鈕的文字,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
iOS實(shí)現(xiàn)毫秒倒計(jì)時的方法詳解
倒計(jì)時在我們?nèi)粘i_發(fā)中必不可少,最近在公司的一個項(xiàng)目中就遇到了這個需求,本文著重介紹的是利用iOS實(shí)現(xiàn)毫秒倒計(jì)時的方法,文中給出了詳細(xì)的示例代碼,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-04-04iOS9 系統(tǒng)分享調(diào)用之UIActivityViewController
UIActivityViewController類是一個標(biāo)準(zhǔn)的view controller,通個使用這個controller,你的應(yīng)用程序就可以提供各種服務(wù)。本文給大家介紹iOS9 系統(tǒng)分享調(diào)用之UIActivityViewController,感興趣的朋友一起學(xué)習(xí)吧2015-11-11iOS開發(fā)中使用Quartz2D繪圖及自定義UIImageView控件
這篇文章主要介紹了iOS開發(fā)中使用Quartz2D繪圖及自定義UIImageView控件的方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11簡介Objective-C解析XML與JSON數(shù)據(jù)格式的方法
這篇文章主要介紹了Objective-C解析XML與JSON數(shù)據(jù)格式的方法,文中解析JSON包括拼接JSON字符串用到了SBJson這個解析器,需要的朋友可以參考下2016-01-01