String 如何在Swift中更改字符串中单个单词的颜色
因此,作为一些上下文,我有一个字典,它根据解析返回的错误代码保存一些自定义错误消息。您可以在下面看到一个:String 如何在Swift中更改字符串中单个单词的颜色,string,swift,dictionary,parse-platform,String,Swift,Dictionary,Parse Platform,因此,作为一些上下文,我有一个字典,它根据解析返回的错误代码保存一些自定义错误消息。您可以在下面看到一个: var parseErrorDict: [Int:String] = [ 203: "This email address \(emailTextField.text) is already registered." ] 我想要的是,将填充为不同颜色或粗体的电子邮件地址。这可能吗 对Swift来说比较新,所以请解释清楚或帮助清楚:)提前谢谢 您希望使用属性化字符串编辑字符串
var parseErrorDict: [Int:String] = [
203: "This email address \(emailTextField.text) is already registered."
]
我想要的是,将填充为不同颜色或粗体的电子邮件地址。这可能吗
对Swift来说比较新,所以请解释清楚或帮助清楚:)提前谢谢 您希望使用属性化字符串编辑字符串的不同部分。在你的例子中,你首先要把字符串分成三个部分,开始、中间和结束。然后,您可以将属性添加到这三个部分,例如,将中间部分(电子邮件地址)设置为红色,然后您可以将这三个部分重新添加到一起:
// 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
我注意到在“合并三部分”部分中,您没有添加第一个AttributeString,您只合并了中间和结尾…?在最后一部分中,将其添加到标签中,在我的情况下,如何执行此操作?因为没有任何标签可供我添加?