import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 创建UILabel
let label = UILabel(frame: CGRectMake(10,20,300,100))
label.text = "标签文字"
self.view.addSubview(label)
// 背景颜色和文字颜色的设置
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
// 对齐方式设置
label.textAlignment = NSTextAlignment.Right
// 文字阴影的设置
label.shadowColor = UIColor.grayColor()
label.shadowOffset = CGSizeMake(-5, 5) //阴影偏移量
// 字体的设置
label.font = UIFont.systemFontOfSize(14)
// 文字过长时的省略方式
label.lineBreakMode = NSLineBreakMode.ByTruncatingTail //隐藏尾部并显示省略号
// 文字大小适应标签宽度
label.adjustsFontSizeToFitWidth = true //当文字超出标签宽度时,自动调整文字大小,使其不被戒断
// 不限制行数
label.numberOfLines = 0
// 设置文本高亮
label.highlighted = true
label.highlightedTextColor = UIColor.greenColor()
// 富文本设置
let attr = NSMutableAttributedString(string: "文字文字文字文字")
attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: NSMakeRange(0, 3)) //设置字体颜色
attr.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(3, 3)) //文字背景颜色
label.attributedText = attr
}
}
Swift - 文本标签(UILabel)的用法
最新推荐文章于 2024-05-11 09:50:35 发布