iOS 开发之基础控件 UILabel
1. UILabel 的使用
let label = UILabel(frame: CGRect(x: 10, y: 30, width: 375, height: 130))
label.text = "自定义简单的便签控件:设置长文本,字体加粗,字号18,颜色为蓝色,阴影为橙色,位置偏移参数为2,文字对齐模式居左,显示行数为4行"
label.font = UIFont.boldSystemFont(ofSize: 18)
label.textColor = UIColor.blue
label.shadowColor = UIColor.orange
label.shadowOffset = CGSize(width: 3, height: 3)
label.textAlignment = NSTextAlignment.left
label.numberOfLines = 4
self.view.addSubview(label)
效果展示:
2. UILabel 设置可变属性文本
let label = UILabel(frame: CGRect(x: 10, y: 150, width: 375, height: 60))
label.font = UIFont.systemFont(ofSize: 14)
label.numberOfLines = 0
let attStr = NSMutableAttributedString(string: "可变属性字符串,可以分段设置字体、颜色、下划线、阴影和超链接。")
attStr.addAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 30), NSAttributedString.Key.foregroundColor:UIColor.black], range: NSRange(location: 0, length: 2))
attStr.addAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 22), NSAttributedString.Key.foregroundColor:UIColor.red], range: NSRange(location: 2, length: 3))
attStr.addAttributes([NSAttributedString.Key.underlineStyle: NSNumber.init(value: 1), NSAttributedString.Key.underlineColor: UIColor.red], range: NSRange(location: 20, length: 3))
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 2, height: 2)
shadow.shadowColor = UIColor.cyan
attStr.addAttributes([NSAttributedString.Key.shadow: shadow], range: NSRange(location: 24, length: 2))
let link = NSString(string: "https://www.baidu.com")
attStr.addAttributes([NSAttributedString.Key.link: link], range: NSRange(location: 27, length: 3))
label.attributedText = attStr
scrollView.addSubview(label)
效果展示:
|