一、Label常见属性
1、设置截断模式
typedef NS_ENUM(NSInteger, NSLineBreakMode) {
NSLineBreakByWordWrapping = 0, // Wrap at word boundaries, default
NSLineBreakByCharWrapping, // Wrap at character boundaries
NSLineBreakByClipping, // Simply clip
NSLineBreakByTruncatingHead, // Truncate at head of line: "...wxyz"
NSLineBreakByTruncatingTail, // Truncate at tail of line: "abcd..."
NSLineBreakByTruncatingMiddle // Truncate middle of line: "ab...yz"
}
2、设置为高亮状态及高亮状态的颜色
highlighted
highlightedTextColor
二、内容自适应Label宽度
minimumScaleFactor
设置最小收缩比例,如果Label宽度小于文字长度时,文字
进行收缩,收缩超过比例后,停止收缩。
adjustsFontSizeToFitWidth
设置字体大小适应label宽度
如果只设置adjustsFontSizeToFitWidth内容会无限小,如果设置最小收缩比例,内容不会无限缩小,超出的部分显示省略号。
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
label.text = @"magicmagicmagicmagicmaigcmagicmagicmagicmagicmaig";
label.backgroundColor = [UIColor purpleColor];
label.adjustsFontSizeToFitWidth = YES;
[self.view addSubview:label];
在实际应用中上面的效果显然是不行的,添加一行代码:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
label.minimumScaleFactor = .5f;
label.text = @"magicmagicmagicmagicmaigcmagicmagicmagicmagicmaig";
label.backgroundColor = [UIColor purpleColor];
//中间截断
label.lineBreakMode = NSLineBreakByTruncatingMiddle;
label.adjustsFontSizeToFitWidth = YES;
[self.view addSubview:label];
三、Label**高度**自适应内容
numberOfLines
设置label显示的行数,为0表示不限制行数
siziToFit
calls sizeThatFits: with current view bounds and changes bounds size.
这个方法会调用sizeThatFits,用当前的bounds改变原有的bounds
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 500, 100)];
view.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 100)];
label.text = @"magicmagicsdjflalsdjfljlasjdlfasmagicmagicmaigcmagicmagicmagicmagicmaig";
label.backgroundColor = [UIColor greenColor];
label.numberOfLines = 0;
[label sizeToFit];
[self.view addSubview:label];
效果如下: