如何在Swift中更改String中的单个单词颜色

时间:2015-09-16 20:54:00

标签: string swift dictionary parse-platform

因此,作为一些上下文,我有一个字典,它根据Parse返回的错误代码保存一些自定义错误消息。你可以在下面看到一个:

var parseErrorDict: [Int:String] = [

    203: "This email address \(emailTextField.text) is already registered." 

]

我想要的是,电子邮件地址将填充为不同的颜色或以粗体显示。这可能吗?

Swift相当新,所以请解释或帮助清楚:)提前谢谢。

1 个答案:

答案 0 :(得分:0)

您希望使用属性字符串来编辑字符串的不同部分。在你的情况下,首先将字符串分解为三个部分,即开始,中间和结尾。然后,您可以为这三个部分添加属性,例如将中间部分(电子邮件地址)设置为红色,然后您可以将这三个部分重新附加在一起:

// The first part of the string should be mutable as parts will be appended to it
var attributedString = NSMutableAttributedString(string: "This email address ")

// Here we specify the attribute that is will be applied to the middle part
var attributes = [NSForegroundColorAttributeName: UIColor.redColor()]
var attributedStringEmail = NSAttributedString(string: "someone@somewhere.com", attributes: attributes)

// The end part
var attributedStringEnd = NSAttributedString(string: " is already registered.")

// Combine the three parts
attributedString.appendAttributedString(attributedStringEmail)
attributedString.appendAttributedString(attributedStringEnd)

// Give the label its text
label.attributedText = attributedString