Search code examples
iosswiftswift3swift4nsattributedstringkey

Swift 4 Conversion error - Type 'NSAttributedStringKey' has no member 'foregroundColorNSAttributedStringKey'


I converted my code from Swift 3 to Swift 4 but getting this error:

Type 'NSAttributedStringKey' has no member 'foregroundColorNSAttributedStringKey'

My code is:

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)

Solution

  • Replace line

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

    with

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

    Also you can use addAttributes method to set more than 1 attribute at a time for a range

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