简体   繁体   English

NSMutableAttributedString 不适用于 ViewController 但适用于 Playground

[英]NSMutableAttributedString not working in ViewController but works in Playground

I have a problem with this code and I do not know what I am doing wrong.我有这个代码的问题,我不知道我做错了什么。 I tried everything in Playground first and it works like a charm.我首先尝试了 Playground 中的所有内容,它的效果非常好。 Assigning this to the UILabel it just not working.将此分配给 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!

I practically have a label that is getting a text from 2 strings.我实际上有一个从 2 个字符串中获取文本的标签。 Those strings I want to be displayed with different colors and fonts.我想用不同的颜色和字体显示那些字符串。 It works in Playground but not in the ViewController.它适用于 Playground 但不适用于 ViewController。 Can anybody help, please?请问有人可以帮忙吗?

In your example you have two different attributed string created from the same original string and you are passing your string without attributes to the label text property.在您的示例中,您从同一个原始字符串创建了两个不同的属性字符串,并且您将没有属性的字符串传递给标签文本属性。 Instead you can create a unique attributed string and you can use it with attributedText property of your label:相反,您可以创建一个唯一的属性字符串,并且可以将其与标签的属性文本属性一起使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM