自定义导航栏返回按钮——2020-07-19

默认导航栏的返回按钮不是很好看,而且还不想要文字,想替换成自己自定义的返回按钮image。
方法还针对iOS 11+进行特殊处理,不然没效果,顺便提一点button是使用
setImage: forState:,而不是setBackgroundImage: forState:

效果图:

代码:

#pragma mark - Override

/// BaseNavigationController
/// 自定义返回按钮 不需要返回按钮标题
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.childViewControllers.count > 0) { // 如果push进来的不是第一个控制器

        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
        UIImage *imageNormal = [[UIImage imageNamed:@"return"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *imageHighlighted = [[imageNormal renderWithColor:UIColor.grayColor] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [button setImage:imageNormal forState:UIControlStateNormal];
        [button setImage:imageHighlighted forState:UIControlStateHighlighted];
        
        // 让按钮内部的所有内容左对齐
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [button addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
        
        if(@available(iOS 11.0, *)) {
            button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);   // 根据自己的要求设置
            button.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);   // 根据自己的要求设置
            // 修改导航栏左边的item
            UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
            viewController.navigationItem.leftBarButtonItem = backBarButtonItem;
        }
        else {
            // 修改导航栏左边的item
            UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
            UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                       target:nil
                                                                                       action:nil];
            // 将宽度设为负值
            spaceItem.width = -15;

            viewController.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
        }


    }
    // 这句super的push要放在后面, 让viewController可以覆盖上面设置的leftBarButtonItem
    [super pushViewController:viewController animated:animated];
}

- (void)pop {
    [self popViewControllerAnimated:YES];
}

你可能感兴趣的:(自定义导航栏返回按钮——2020-07-19)