我对此代码有疑问,我不知道我做错了什么。我首先在Playground尝试了一切,它就像一个魅力。将此分配给UILabel它只是不起作用。
let nameSurname = "\(postAddSetup.nameSurname.text!)"
let checkIn = " - \(setLocationPlace), \(setLocationCity)"
var string = postAddSetup.nameSurname.text
string = "\(nameSurname) \(checkIn)"
let boldUsername = NSMutableAttributedString(string: string!)
boldUsername.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: (string! as NSString).range(of: nameSurname))
let normalCheckIn = NSMutableAttributedString(string: string!)
normalCheckIn.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 11), range: (string! as NSString).range(of: checkIn))
normalCheckIn.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: (string! as NSString).range(of: checkIn))
print(string!)
postAddSetup.nameSurname.text = string!
我几乎有一个从2个字符串中获取文本的标签。那些字符串我想用不同的颜色和字体显示。它适用于Playground但不适用于ViewController。请帮忙吗?
答案 0 :(得分:1)
在您的示例中,您有两个不同的属性字符串,它们是从相同的原始字符串创建的,并且您将没有属性的字符串传递给标签文本属性。 相反,您可以创建唯一的属性字符串,并且可以将其与标签的attributedText属性一起使用:
var string = postAddSetup.nameSurname.text
string = "\(nameSurname) \(checkIn)"
let attributedString = NSMutableAttributedString(string: string!)
attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 14), range: (string! as NSString).range(of: nameSurname))
attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 11), range: (string! as NSString).range(of: checkIn))
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: (string! as NSString).range(of: checkIn))
postAddSetup.nameSurname.attributedText = attributedString