iOS 11 uses method swizzling to remove the text of the return button from the navigation bar

Method 1: set the text style of BarButtonItem to transparent color, and the code is as follows:

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

 

In addition, this method will cause the title not to be centered and offset a lot, as shown below (although it is not displayed, it also occupies a large part of the left side of the navigation bar)

 

Method 2: add a category to UIViewController, and then replace viewdidappearance with method swziling in the load method. Some codes are as follows

+(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);
    }
}

 

matters needing attention:

  • To assign a value to the entire backButtonItem, A kind of This method does not work, because backBarButtonItem is empty by default, and the default declaration does not execute when the nil method message is given (refer to Official website)
self.navigationItem.backBarButtonItem.title = @" ";

 

  • Display relationship between leftBarButtonItem and backBarButtonItem:
    If there is a leftBarButtonItem, the leftBarButtonItem of the current VC will be displayed first. If there is no one, the backBarButtonItem of the last VC will be displayed. If there is no one, the title of the last VC will be displayed (refer to Official website It's explained clearly on the official website.)
 

 

Tags: iOS

Posted on Sat, 21 Mar 2020 12:11:33 -0400 by ErikTheViking