要实现上面这个功能其实有很多方法,我这里介绍两种方法来实现,一种是通过我们创建一个view,然后往这个view里面加入两个label,然后我们再设置自动布局的约束
//设置titleView
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
//导航栏的titleView为我们自定义的titleView
navigationItem.titleView = titleView
///创建titleLabel,就是发微博的label
let titleLabel:UILabel = UILabel(title: "发动态", color: UIColor.black, fontSize: 15)
///创建nameLabel
let nameLabel:UILabel = UILabel(title: "哈哈哈",
color: UIColor.lightGray, fontSize: 13)
//添加子控件
titleView.addSubview(titleLabel)
titleView.addSubview(nameLabel)
//titleLabel设置自动布局
titleLabel.mas_makeConstraints { (make) in
//设置中心点X的自动布局
make?.centerX.mas_equalTo()(titleView.mas_centerX)
//设置顶部的自动布局
make?.top.mas_equalTo()(titleView.mas_top)
}
//设置nameLabel的自动布局
nameLabel.mas_makeConstraints { (make) in
//设置中心点X的布局
make?.centerX.mas_equalTo()(titleView.mas_centerX)
//设置顶部的自动布局
make?.top.mas_equalTo()(titleLabel.mas_bottom)
//设置底部的自动布局
make?.bottom.mas_equalTo()(titleView.mas_bottom)
}
}
另外一种就是通过label来显示,然后通过设置label的attributedText属性来进行设置,换行我们这里可以通过\n,换行符来做
//创建一个Label
UILabel * titleView=[[UILabel alloc]init];
//显示宽高
titleView.w=180;
titleView.h=44;
//设置文字居中显示
titleView.textAlignment=NSTextAlignmentCenter;
//设置titleLabel自动换行
titleView.numberOfLines=0;
//设置发微博的prefix
NSString * prefix=@"发动态";
NSString * name = @"哈哈哈"
//获取标题的字符串
NSString * str=[NSString stringWithFormat:@"%@\n%@",prefix,name];
//创建一个带有属性的字符串比如说颜色,字体等文字的属性
NSMutableAttributedString * attrStr=[[NSMutableAttributedString alloc]initWithString:str];
//设置name的字体大小
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[str rangeOfString:name]];
//设置发动态的字体大小
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:[str rangeOfString:prefix]];
//设置name的颜色
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:[str rangeOfString:name]];
//label中也可以携带图片
// NSTextAttachment * attachment=[[NSTextAttachment alloc]init];
// attachment.image=[UIImage imageNamed:@""];
// NSAttributedString * str2=[NSAttributedString attributedStringWithAttachment:attachment];
// [attrStr appendAttributedString:str2];
//设置有属性的text
titleView.attributedText=attrStr;
//设置导航栏的titleView
self.navigationItem.titleView=titleView;