How to change colour of the certain words in label

2019-04-02 11:06发布

This question already has an answer here:

Created a Label with a simple text.

How can I change the color of the certain words in the label?

Swift 3

Like below-

Expected result

1条回答
ら.Afraid
2楼-- · 2019-04-02 11:56

Use NSMutableAttributedString to apply colors for different words in a string. Try this, there are already lot of similar questions have the answers in SO.

let myLabel = UILabel()
var stringOne = "Swift 3 has come"
let stringTwo = "has"

let range = (stringOne as NSString).range(of: stringTwo)

let attributedText = NSMutableAttributedString.init(string: stringOne)
attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: range)
myLabel.attributedText = attributedText
查看更多
登录 后发表回答