02.设置backBarButtonItem以及导航栏背景色

如图,我们想要设置导航栏背景色为黑色:


首先最常用的就是:[UINavigationBar appearance],可以在继承的NavigationController里边对navigationBar进行统一的设置,

但是直接设置它的背景色backgroundColor:

UINavigationBar *navBar = [UINavigationBar appearance];
navBar.backgroundColor = [UIColor blackColor];

得到却是这样的结果:


正确的做法是设置它的barTintColor

navBar.barTintColor = [UIColor blackColor];

状态栏默认是黑色,而现在我们需要设置为白色,实现以下方法即可:

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

导航栏背景色设置完毕以后,我们需要设置backBarButtonItem,默认的backBarButtonItem是"<返回",但是我们只想要"<"这个箭头。那么该怎么办呢,首先我们想到的可能就是使用一张带箭头图片,给leftBarButtonItem赋值,为了避免每个页面都设置leftBarButtonItem,我们需要定义一个父类UIViewController,让我们的Controller继承于它。但是这样有个弊端就是当我们使用UITableViewController,又得定义一个父类继承于它。在这里找到一个简便的全局设置方法:

// 设置返回item只保留箭头
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
将文字向上偏移,这样文字就被隐藏了,只剩下"<",符合我们的需求。
以下是所有代码:

TSLNavigationController.h

#import <UIKit/UIKit.h>

@interface TSLNavigationController : UINavigationController

@end
TSLNavigationController.m
#import "TSLNavigationController.h"

@interface TSLNavigationController ()

@end

@implementation TSLNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置导航栏属性
    UINavigationBar *navBar = [UINavigationBar appearance];
    navBar.barTintColor = [UIColor blackColor];
    navBar.tintColor = [UIColor whiteColor];
    // navBar.backgroundColor = [UIColor blackColor];
    // 设置title属性
    NSMutableDictionary *titleTextAttrs = [NSMutableDictionary dictionary];
    titleTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    titleTextAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:17];
    [navBar setTitleTextAttributes:titleTextAttrs];
    // 设置返回item只保留箭头
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
}

/**
 *  设置状态栏字体颜色
 */
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

未完待续...

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值