【问题标题】:How to change a single words colour in a String in Swift如何在 Swift 中更改字符串中单个单词的颜色
【发布时间】:2015-09-16 20:53:59
【问题描述】:

因此,作为某些上下文,我有一个字典,其中包含一些自定义错误消息,基于 Parse 返回的错误代码。您可以在下面看到一个:

var parseErrorDict: [Int:String] = [

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

]

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

对 Swift 相当陌生,所以请清楚地解释或帮助 :) 在此先感谢。

【问题讨论】:

    标签: string swift dictionary parse-platform


    【解决方案1】:

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

    // 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
    

    【讨论】:

    • 我注意到在组合三部分部分,你没有添加第一个属性字符串,你只组合了中间和结尾...?
    • 在最后一部分,将它添加到标签中,在我的情况下我该怎么做?因为我没有任何标签可以添加它?
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2015-12-22
    • 1970-01-01
    • 2015-09-23
    • 2014-02-15
    相关资源
    最近更新 更多