iOS swift5 改变UILabel上指定文字的颜色和字体
·
1. 效果

2.代码
代码1
class tableViewTestVC: UIViewController{
lazy var label:UILabel = {
let label = UILabel()
label.backgroundColor = .yellow
let font = UIFont.init(name: "PingFang SC", size: 14)!
label.font = font
label.numberOfLines = 0
let str:NSString = "但是公司的 高度 是广东省公司的广东省高速度 高度 来开个大帅哥多撒谎"
label.text = str as String
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
label.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(30)
make.left.equalToSuperview().offset(10)
make.width.equalTo(200)
}
let labelText = label.text!
let range:Range = labelText.range(of: "高度")!
let nsrange = labelText.nsRange(from: range)
let mutableAttribute = NSMutableAttributedString(attributedString: label.attributedText!)
mutableAttribute.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font : UIFont.init(name: "PingFang SC", size: 14)!], range: nsrange)
label.attributedText = mutableAttribute
}
}
extension String {
/// range转换为NSRange
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
}
代码2(推荐)
func getAttributedString(str1: String, str2: String) -> NSMutableAttributedString {
var attriText = NSMutableAttributedString(string: str1 + str2)
let index = str1.count
attriText.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.black, NSAttributedString.Key.font : UIFont.init(name: "Helvetica-Bold", size: 23)!], range: NSRange(location: 0, length: index))
attriText.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.black, NSAttributedString.Key.font : UIFont.init(name: "PingFang SC", size: 15)!], range: NSRange(location: index, length: attriText.string.count - index))
return attriText
}
bStepValueLabel.attributedText = getAttributedString(str1: "36", str2: "步")
更多推荐


所有评论(0)