iOS - 设置导航栏之标题栏居中、标题栏的背景颜色
本章实现效果:

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;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2016-06-20 java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.copyof