1.描述
class UILabel : UIView
UILabel继承自UIView
苹果官方文档:
A view that displays one or more lines of informational text.(是一个描述一行或者多行文本信息的视图)
UILabel支持展示属性字符串(attributed strings).并且支持多行展示,如果设置好约束,还可以进行高度的自适应.
UILabel大多通过NSString赋值给text或者NSAttributeString给attributeText来展示内容.
2.代码实例
let myLabel = UILabel()
view.addSubview(myLabel)
myLabel.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
myLabel.backgroundColor = UIColor.red
myLabel.text = "Hello UILabel"
//设置字体样式
myLabel.font = UIFont.systemFont(ofSize: 15)
//右对齐
myLabel.textAlignment = NSTextAlignment.right
//头部截取
myLabel.lineBreakMode = NSLineBreakMode.byTruncatingHead
//不可编辑状态--会字体变灰
myLabel.isEnabled = false;
//继承自UIView,设置是否可以相应用户交互,默认值为false
myLabel.isUserInteractionEnabled = true;
//preferredMaxLayoutWidth
myLabel.text = "Hello UILabel,Hello UILabel,Hello UILabel,Hello UILabel"
myLabel.numberOfLines = 0;
myLabel.translatesAutoresizingMaskIntoConstraints = false
let constraintArrayH = NSLayoutConstraint.constraints(withVisualFormat: "H:|-100-[customLabel]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["customLabel":myLabel])
let constraintArrayV = NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[customLabel]", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["customLabel":myLabel])
self.view.addConstraints(constraintArrayH)
self.view.addConstraints(constraintArrayV)
//用于约束层面控制字符串宽的的属性
myLabel.preferredMaxLayoutWidth = 100
//多属性字符串作为展示内容
let aString: NSMutableAttributedString = NSMutableAttributedString.init(string: "Hello UILabel with NSAttributedString")
let range = NSMakeRange(0, 5)
aString.setAttributes([NSAttributedString.Key.foregroundColor:UIColor.green],range:range)
myLabel.attributedText = aString;
print("Hello UILabel")
- 工程下载地址:待补充
3.总结
UILable是常用的用于展示文本信息的控件,详情请参考苹果官方文档:UIKit->UILabel