在字符串后添加标签
Add a label after a String
我需要用两种颜色创建一行文本
会有一个文本,它是黑色的字符串,还有一个 $ 符号,它应该是红色的。
lazy var dollarSmb: UILabel = {
let smb = UILabel()
smb.text = "$"
smb.font = UIFont.systemFont(ofSize: 17, weight: .regular)
smb.textColor = UIColor.red
smb.baselineAdjustment = .alignCenters
smb.translatesAutoresizingMaskIntoConstraints = false
return smb
}()
我想在标签字符串之后添加它,类似这样:
Var label = "This is a test" + " \(dollarSmb)"
没用
谁能帮我找到最好的方法?
非常感谢
您可以使用 NSAttributedString
构造具有不同颜色的单个字符串。
let attributedString = NSMutableAttributedString(string: "This is a test ")
let dollarSymbl = NSAttributedString(string: "$", attributes: [.foregroundColor: UIColor.red])
attributedString.append(dollarSymbl)
// Then assign it to a UILabel
label.attributedText = attributedString
使用 NSAttributedString
而不是设置 smb.text
,而是设置 smb.attributedText
。
类似
smb.attributedText = NSAttributedString(string: "$", attributes [.foregroundColor: UIColor.red])
我需要用两种颜色创建一行文本
会有一个文本,它是黑色的字符串,还有一个 $ 符号,它应该是红色的。
lazy var dollarSmb: UILabel = {
let smb = UILabel()
smb.text = "$"
smb.font = UIFont.systemFont(ofSize: 17, weight: .regular)
smb.textColor = UIColor.red
smb.baselineAdjustment = .alignCenters
smb.translatesAutoresizingMaskIntoConstraints = false
return smb
}()
我想在标签字符串之后添加它,类似这样:
Var label = "This is a test" + " \(dollarSmb)"
没用
谁能帮我找到最好的方法? 非常感谢
您可以使用 NSAttributedString
构造具有不同颜色的单个字符串。
let attributedString = NSMutableAttributedString(string: "This is a test ")
let dollarSymbl = NSAttributedString(string: "$", attributes: [.foregroundColor: UIColor.red])
attributedString.append(dollarSymbl)
// Then assign it to a UILabel
label.attributedText = attributedString
使用 NSAttributedString
而不是设置 smb.text
,而是设置 smb.attributedText
。
类似
smb.attributedText = NSAttributedString(string: "$", attributes [.foregroundColor: UIColor.red])