【问题标题】:Multiple text color for UILabel text does not work in swift 3.0UILabel 文本的多种文本颜色在 swift 3.0 中不起作用
【发布时间】:2016-11-03 07:09:45
【问题描述】:

我尝试更改UILabel 部分的文本颜色,如下所示。

func changetheColor () {
        let staticStrng : String = "Zave receipt"
        var mymutableAttributeString = NSMutableAttributedString()
        mymutableAttributeString = NSMutableAttributedString(string: staticStrng)

        mymutableAttributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: 5,length: 7))
        saveReceiptLabel.text = mymutableAttributeString.string
    }

这不起作用,我做错了什么。希望您的帮助。

【问题讨论】:

  • 将最后一行替换为saveReceiptLabel.attributedText = mymutableAttributeString。具有颜色(以及可能的其他渲染效果)和字符串的是 NSAttributedString,而不是只是一个字符链的 (NS)String。
  • 我试过了,然后报错cannot assign value of type NSMutableAttributedString of type String
  • saveReceiptLabel.attributedText =,而不是saveReceiptLabel.text =,这是您对我的建议的尝试吗?
  • 是的,明白了。那是我错过了。谢谢

标签: ios uilabel swift3 textcolor nsmutableattributedstring


【解决方案1】:

改变这个:

    saveReceiptLabel.attributedText = mymutableAttributeString.string

【讨论】:

  • @AnuradhS:这段代码真的有效吗,因为最后是mymutableAttributeString.string而不是mymutableAttributeString
  • @Larme 是的,我已经在没有 attributedText 部分的情况下使用了它。在 swift 3 中,我们只使用 mymutableAttributeString 它会给你一个错误,叫做` cannot assign value of type NSMutableAttributedString of type String`
  • @AnuradhS 我不使用 Swift,但对我来说它是 myLabel.text = myAttributedString.stringmyLabel.attributedText = myAttributedString,不会有相同的效果,但你应该不能混合使用它们。
  • @Larme 它对我来说很好,如果我不使用 .string 它会给我一个错误。
  • 很奇怪。它不应该。 saveReceiptLabel.attributedText = mymutableAttributeString.string => “无法将 'String' 类型的值赋给类型 'NSAttributedString?'”和 saveReceiptLabel.text = mymutableAttributeString => “无法将 'NSMutableAttributedString' 类型的值赋给类型 'String?'”,这是有道理的。跨度>
猜你喜欢
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多