let label : UILabel = UILabel(frame: CGRect(x: button.frame.origin.x, y: button.frame.origin.y + 150, width: 200, height: 50))
label.lineBreakMode = .byTruncatingTail
label.adjustsFontSizeToFitWidth = true
label.highlightedTextColor = UIColor.cyan
label.font = UIFont.systemFont(ofSize: 20)
self.view.addSubview(label)
//显示文本内容
label.text = "hello 2018 北京见"
//背景颜色
label.backgroundColor = UIColor.red
//文字颜色
label.textColor = UIColor.white
//文字对齐方式
label.textAlignment = NSTextAlignment.center
/阴影颜色 testLable.shadowColor = UIColor.black //阴影偏移位置 testLable.shadowOffset = CGSize(width:-5,height:5) //根据视图宽度自动调整文字大小 testLable.adjustsFontSizeToFitWidth = true //高亮时候的文字颜色 testLable.highlightedTextColor = UIColor.cyan //设置圆角 testLable.layer.cornerRadius = 20
testLable.layer.masksToBounds = true
//边框的宽度和颜色
testLable.layer.borderColor = UIColor.green.cgColor
testLable.layer.borderWidth = 2
//文字类型/大小
testLable.font = UIFont.boldSystemFont(ofSize: 20)
//加粗类型
testLable.font = UIFont.systemFont(ofSize: 20)/
/文字大小 testLable.font =
UIFont.italicSystemFont(ofSize: 20)//斜体类型
//大小和文字一起设置
testLable.font = UIFont(name:"您好",size:50)
//显示样式
testLable.lineBreakMode = NSLineBreakMode.byCharWrapping
//多行显示
label.numberOfLines = 2//最多显示2行
label.numberOfLines = 0// 默认没有行数显示
label.numberOfLines = 1//只能显示一行
let attributeString = NSMutableAttributedString(string: "hello 2018 北京见")
attributeString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSMakeRange(0, 6))
//设置背景颜色
attributeString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.cyan, range: NSMakeRange(0, 3))
//设置下划线
attributeString.addAttribute(NSAttributedStringKey.underlineStyle, value:NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(6,4))
label.attributedText = attributeString
富文本效果图
/// 动态计算Label宽度
func getLabelWidth(str: String, font: UIFont, height: CGFloat)-> CGFloat {
let statusLabelText: NSString = str as NSString
let size = CGSize(width: CGFloat(MAXFLOAT), height: height)
let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : font], context: nil).size
return strSize.width
}
/// 动态计算Label高度
func getLabelHegit(str: String, font: UIFont, width: CGFloat)-> CGFloat {
let statusLabelText: NSString = str as NSString
let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : AnyObject], context: nil).size
return strSize.height
}
网友评论