设置导航控制器UIBarButtonItem的样式

方法一:
重复使用需要抽取代码

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"写私信" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
     [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
     [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    // 设置按钮文字的尺寸 为 按钮自己的尺寸
    button.size = [button.currentTitle sizeWithFont:button.titleLabel.font];
    // 监听按钮点击
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
     self.navigationItem.rightBarButtonItem.enabled = NO;

方法二:
直接在自定义导航控制器设置

+(void)initialize{
    //通过appearance对象能修改整个项目中的UIBarButtonItem的样式
    UIBarButtonItem *appearance = [UIBarButtonItem appearance];
    //设置普通状态下的文字属性
    NSMutableDictionary *textDict = [NSMutableDictionary dictionary];
    textDict[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    textDict[NSForegroundColorAttributeName] = [UIColor orangeColor];
    [appearance setTitleTextAttributes:textDict forState:UIControlStateNormal];
    
    //设置高亮状态下的文字属性
    NSMutableDictionary *hightextDict = [NSMutableDictionary dictionary];
    hightextDict[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    hightextDict[NSForegroundColorAttributeName] = [UIColor redColor];
    [appearance setTitleTextAttributes:hightextDict forState:UIControlStateHighlighted];
    
    //设置不可用状态的文字属性
    NSMutableDictionary *disableTextDict = [NSMutableDictionary dictionary];
    disableTextDict[NSFontAttributeName] = [UIFont systemFontOfSize:15];
    disableTextDict[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
    [appearance setTitleTextAttributes:disableTextDict forState:UIControlStateDisabled];
    
}

你可能感兴趣的:(设置导航控制器UIBarButtonItem的样式)