I need to create a line of text with two colors
There will Be a text, which is string in black and there will be one $ Symbol and it should be 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
}()
And I want to add it after the label string, something like that:
Var label = "This is a test" + " \(dollarSmb)"
It's not working
Could anyone help me the best way to do that? Many thanks
You could use NSAttributedString
to construct a single string with a different color.
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