Swift 4
(Примечание: обозначение приписываемой строкового ключа изменяется в быстром 4)
Вот это расширение для NSMutableAttributedString
, что добавить/набор цвет на строки/текста.
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Теперь попробуйте выше расширение с UILabel
и увидеть результат
let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let title = "Name"
let star = "*"
let stringValue = "\(title) \(star)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: star) // or use direct value for text "red"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
NSAttributedString ... см Http: // StackOverflow.com/questions/3482346/how-do-you-use-nsattributedstring –
http://stackoverflow.com/questions/3786528/iphone-ipad-how-exactly-use-nsattributedstring – ajithmn89
Вы ориентируетесь на iOS 6.0 и выше? – Bartu