1. 初始化UILebl
//创建区域位置
let rect = CGRect(x: 100, y: 200, width: 200, height: 40)
let label = UILabel(frame: rect)
//文本内容
label.text = "Hello, Jack!"
//添加到视图中
self.view.addSubview(label)
2.字体、大小、加粗
label.font = UIFont(name: "Arial", size: 14)
label.font = UIFont.boldSystemFont(ofSize: 20)
3.颜色设置
//背景颜色
label.backgroundColor = UIColor.yellow
//字体颜色
label.textColor = UIColor.red
//RGB方式
label.textColor = UIColor.init(red: 255, green: 0, blue: 0, alpha: 1)
4.对齐方式
label.textAlignment = .left
/*
left 左对齐
center 居中对齐
right 右对齐
justified
natural
*/
5.文字阴影
//阴影颜色
label.shadowColor = UIColor.black
//阴影位置
label.shadowOffset = CGSize(width: -2, height: 2)
6.文本显示
//显示几行
label.numberOfLines = 0 //0:不限制
//显示宽度是否自适应
label.adjustsFontSizeToFitWidth = true
//超出宽度截断方式
label.lineBreakMode = .byTruncatingTail
/*
.byTruncatingHead 隐藏头部并显示省略号: ...xyz
.byTruncatingTail 隐藏尾部并显示省略号: abc...
.byTruncatingMiddle 截断中间部分并显示省略号: abc...xyz
.byClipping 截取多余部分也不显示省略号: abc
*/
7.文本高亮
//是否开启高亮
label.isHighlighted = true
//高亮颜色
label.highlightedTextColor = UIColor.green
8.圆角属性
//是否开启圆角
label.layer.masksToBounds = true
//圆角半径
label.layer.cornerRadius = 5
//边框宽度
label.layer.borderWidth = 2
//边框颜色
label.layer.borderColor = UIColor.blue.cgColor
9.富文本
let attributeString = NSMutableAttributedString.init(string:"welcome hello world")
attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.purple],
range: NSRange.init(location: 0, length: attributeString.length/2))
label.attributedText = attributeString
部分效果如下: