【问题标题】:Swift 4 Conversion error - Type 'NSAttributedStringKey' has no member 'foregroundColorNSAttributedStringKey'Swift 4 转换错误 - 类型“NSAttributedStringKey”没有成员“foregroundColorNSAttributedStringKey”
【发布时间】:2018-07-23 14:01:14
【问题描述】:

我将我的代码从 Swift 3 转换为 Swift 4,但出现此错误:

类型“NSAttributedStringKey”没有成员“foregroundColorNSAttributedStringKey”

我的代码是:

let labelText = NSMutableAttributedString(string: (self.productDetailsInfo?.productAttributes?[indexPath.row].Name as String?)!)
labelText.append(NSAttributedString(string:"*"))
let selectedRange = NSMakeRange(labelText.length - 1, 1);
labelText.addAttribute(NSAttributedStringKey.foregroundColorNSAttributedStringKey.foregroundColor, value: UIColor.red, range: selectedRange)
labelText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: selectedRange)

【问题讨论】:

  • 删除那行labelText.addAttribute(NSAttributedStringKey.foregroundColorNSAttributedStringKey.foregroundColor, value: UIColor.red, range: selectedRange),手动重做,让自动补全帮助你。

标签: ios swift swift3 swift4 nsattributedstringkey


【解决方案1】:

在 Swift 4 中设置前景色属性:

[NSForegroundColorAttributeName: UIColor.white]

【讨论】:

    【解决方案2】:

    foregroundColorNSAttributedStringKeyNSAttributedString.Key中列出了这样的属性

    foregroundColor直接与NSAttributedString.Key一起使用

    在您的代码中将NSAttributedStringKey.foregroundColorNSAttributedStringKey.foregroundColor 替换为NSAttributedStringKey.foregroundColor

    试试这个:

    let labelText = NSMutableAttributedString(string: (self.productDetailsInfo?.productAttributes?[indexPath.row].Name as String?)!)
    labelText.append(NSAttributedString(string:"*"))
    let selectedRange = NSMakeRange(labelText.length - 1, 1);
    
    
    // Remove foregroundColorNSAttributedStringKey
    // Swift 4.1
    labelText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: selectedRange)
    labelText.addAttribute(NSAttributedStringKey.baselineOffset, value: 2, range: selectedRange)
    
    
    // Swift 4.2
    labelText.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: selectedRange)
    labelText.addAttribute(NSAttributedString.Key.baselineOffset, value: 2, range: selectedRange)
    

    【讨论】:

      【解决方案3】:

      换行

        labelText.addAttribute(NSAttributedStringKey.foregroundColorNSAttributedStringKey.foregroundColor, value: UIColor.red, range: selectedRange)
      

        labelText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: selectedRange)
      

      您也可以使用addAttributes 方法为一个范围一次设置多个属性

        labelText.addAttributes([NSAttributedStringKey.foregroundColor:UIColor.red,NSAttributedStringKey.backgroundColor:UIColor.blue], range: selectedRange)
      

      【讨论】:

      • “String”类型的值没有成员“addAttribute”
      猜你喜欢
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多