先看效果图
GITHUB项目源码 常规创建一个简单的label//宽高宏定义let ScreenWidth = UIScreen.main.bounds.widthlet ScreenHeight = UIScreen.main.bounds.height//常规创建self.view.backgroundColor = UIColor.white let label = UILabel(frame:CGRect(x:10, y:20, width:ScreenWidth-20, height:ScreenHeight/4))label.backgroundColor = UIColor.lightGraylabel.text = "这是一条测试的显示数据,this is a test data,但是还不够长,suo yi yao gei ta jia chang yi dian dian"self.view.addSubview(label)复制代码
下面是label的一些常用属性设置
// 颜色label.textColor = UIColor.red// 字体label.font = UIFont.systemFont(ofSize: 24)// 对齐方式label.textAlignment = NSTextAlignment.center// 多行显示label.numberOfLines = 3// 阴影label.shadowColor = UIColor.yellowlabel.shadowOffset = CGSize.init(width:2, height:2)label.lineBreakMode = NSLineBreakMode.byTruncatingTail// 高亮label.isHighlighted = truelabel.highlightedTextColor = UIColor.green复制代码
label的富文本属性设置
// 富文本let attributeString = NSMutableAttributedString.init(string: "这是一条测试富文本的字符串")//从文本0开始6个字符字体HelveticaNeue-Bold,16号attributeString.addAttribute(NSAttributedStringKey.font, value: UIFont.init(name: "HelveticaNeue-Bold", size: 23) ?? UIFont.boldSystemFont(ofSize: 23), range: NSRange.init(location: 0, length: 6))//设置富文本字体颜色attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.brown, range: NSMakeRange(0, 6))//设置文字背景颜色attributeString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.red, range: NSMakeRange(6, 5))label.attributedText = attributeString复制代码