日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

iOS - 设置导航栏之标题栏居中、标题栏的背景颜色

發(fā)布時(shí)間:2025/3/18 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 iOS - 设置导航栏之标题栏居中、标题栏的背景颜色 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本章實(shí)現(xiàn)效果:

Untitled.gif
前言:

項(xiàng)目中很多需求是要求自定義標(biāo)題欄居中的,本人最近就遇到這中需求,如果用系統(tǒng)自帶的titleView設(shè)置的話,不會(huì)居中,經(jīng)過(guò)嘗試,發(fā)現(xiàn)titleview的起點(diǎn)位置和尺寸依賴于leftBarButtonItem和rightBarButtonItem的位置。下面給出我的解決方案

首先自定義一個(gè)標(biāo)題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;//標(biāo)題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; }
具體用法如下:

在當(dāng)前頁(yè)面的控制中只要寫,即可實(shí)現(xiàn)上圖的效果

CustomTitleView *titleView = [[CustomTitleView alloc] init];titleView.backgroundColor = [UIColor greenColor];titleView.frame = CGRectMake(0, 0, PDScreeenW, 44); titleView.title = @"我是標(biāo)題"; self.navigationItem.titleView = titleView; self.titleView = titleView; UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil]; self.navigationItem.rightBarButtonItem = rightBarButtonItem;

總結(jié)

以上是生活随笔為你收集整理的iOS - 设置导航栏之标题栏居中、标题栏的背景颜色的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。