1. 程式人生 > >iOS - 設置導航欄之標題欄居中、標題欄的背景顏色

iOS - 設置導航欄之標題欄居中、標題欄的背景顏色

nor right rect set line cati int tail 自定義

本章實現效果:
技術分享
Untitled.gif
前言:

項目中很多需求是要求自定義標題欄居中的,本人最近就遇到這中需求,如果用系統自帶的titleView設置的話,不會居中,經過嘗試,發現titleview的起點位置和尺寸依賴於leftBarButtonItem和rightBarButtonItem的位置。下面給出我的解決方案

首先自定義一個標題View
#import <UIKit/UIKit.h>
@interface CustomTitleView : UIView
@property (nonatomic, copy) NSString *title;
@end


#import "CustomTitleView.h"
#import "Masonry.h"

@interface CustomTitleView ()
@property(nonatomic,strong)UILabel * titleLabel;//標題label
@property (nonatomic,strong) UIView *contentView;

@end

@implementation CustomTitleView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addSubview:self.contentView];
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.greaterThanOrEqualTo(self);
            make.right.lessThanOrEqualTo(self);
            make.center.equalTo(self);
            make.bottom.top.equalTo(self);
        }];

        [self.contentView addSubview:self.titleLabel];

        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.centerX.equalTo(self.contentView);
        }];

    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self layoutIfNeeded];
}

- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [UIView new];
    }
    return _contentView;
}

-(UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont boldSystemFontOfSize:17];
        _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [_titleLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
        _titleLabel.backgroundColor = [UIColor redColor];
    }
    return _titleLabel;
}

- (void)setTitle:(NSString *)title
{
    self.titleLabel.text = title;
}
具體用法如下:

在當前頁面的控制中只要寫,即可實現上圖的效果

  CustomTitleView *titleView = [[CustomTitleView alloc] init];
    titleView.backgroundColor = [UIColor greenColor];
    titleView.frame = CGRectMake(0, 0, PDScreeenW, 44);
    titleView.title = @"我是標題";
    self.navigationItem.titleView = titleView;
    self.titleView = titleView;

    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

iOS - 設置導航欄之標題欄居中、標題欄的背景顏色