1. 程式人生 > >iOS 11 使用方法替換(Method Swizzling),去掉導航欄返回按鈕的文字

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

uiview iba AD implement lai navig sele selector nal

方法一:設置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),去掉導航欄返回按鈕的文字