UILabel
是iOS中最基本的一个控件,用来展示一段不可编辑的文本。UILabel
继承于UIView
,包含继承于UIView
的属性,可查看iOS UIView控件。
1. UILabel的主要属性
// 显示文本
@property(nullable, nonatomic,copy) NSString *text;
// 文本的颜色,默认为黑色
@property(null_resettable, nonatomic,strong) UIColor *textColor;
// 字体以及大小,默认为系统字体
@property(null_resettable, nonatomic,strong) UIFont *font;
// 文字的对齐方式,默认是NSTextAlignmentLeft左对齐
@property(nonatomic) NSTextAlignment textAlignment;
// 文字长度超出范围时文字的显示方式
@property(nonatomic) NSLineBreakMode lineBreakMode;
// 文本显示的行数,设置为0 即为自动换行
@property(nonatomic) NSInteger numberOfLines;
// 默认是YES,设置为NO将会使文本变暗,表示它没有激活
@property(nonatomic,getter=isEnabled) BOOL enabled;
// 文本高亮颜色
@property(nullable, nonatomic,strong)UIColor *highlightedTextColor;
// 是否高亮显示
@property(nonatomic,getter=isHighlighted) BOOL highlighted;
// 阴影颜色
@property(nullable, nonatomic,strong) UIColor *shadowColor;
// 阴影偏移量,默认是(0, -1)
@property(nonatomic) CGSize shadowOffset;
// 根据宽度调整font,默认为NO
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;
// 最小收缩比例
@property(nonatomic) CGFloat minimumScaleFactor;
// 标签属性文本
@property(nullable, nonatomic,copy) NSAttributedString *attributedText;
标签属性文本,详见iOS AttributedString简介
textAlignment
对齐方式
对齐方式 | 说明 |
---|---|
NSTextAlignmentLeft | 左对齐 |
NSTextAlignmentRight | 右对齐 |
NSTextAlignmentCenter | 居中 |
显示如下
lineBreakMode
显示方式
显示方式 | 说明 |
---|---|
NSLineBreakByTruncatingHead | 缩略头部 |
NSLineBreakByTruncatingTail | 缩略尾部 |
NSLineBreakByTruncatingMiddle | 缩略中部 |
NSLineBreakByWordWrapping | 以空格为边界,保留单词 |
NSLineBreakByCharWrapping | 保留整个字符 |
NSLineBreakByClipping | 简单剪裁,到边界截断 |
下图中,第一条是默认显示
numberOfLines
设置为0
adjustsFontSizeToFitWidth
设置为YES
enabled
设置为NO
highlightedTextColor
设置为[UIColor redColor]
,highlighted
设置为YES
下图中,第一条是正常情况,第二条ShadowColor
设置为[UIColor magentaColor]
,ShadowOffset
设置为(10, 5)
2. UILabel高度计算
boundingRectWithSize:options:attributes:context:
计算文本高度
NSString *text = @"Copyright (c) 2006-2018 Apple Inc. All rights reserved.";
UILabel *boundsLabel = [[UILabel alloc] init];
boundsLabel.backgroundColor = [UIColor brownColor];
boundsLabel.text = text;
boundsLabel.numberOfLines = 0;
boundsLabel.font = [UIFont systemFontOfSize:17];
NSInteger option = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [text boundingRectWithSize:CGSizeMake(320, CGFLOAT_MAX) options:option
attributes:@{NSFontAttributeName: boundsLabel.font} context:nil];
boundsLabel.frame = CGRectMake(30, 100, 320, ceilf(rect.size.height) + 1);
[self.view addSubview:boundsLabel];
显示如下