KhanShaheb
KhanShaheb

Reputation: 714

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)

Upvotes: 2

Views: 6663

Answers (3)

Ammar Mujeeb
Ammar Mujeeb

Reputation: 1311

In Swift 4 to set foreground color attribute:

[NSForegroundColorAttributeName: UIColor.white]

Upvotes: 1

Krunal
Krunal

Reputation: 79746

There is such kind of property foregroundColorNSAttributedStringKeylisted in NSAttributedString.Key

Use foregroundColor directly with NSAttributedString.Key

Replace NSAttributedStringKey.foregroundColorNSAttributedStringKey.foregroundColor with NSAttributedStringKey.foregroundColor in your code.

Try this:

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)

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100543

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)

Upvotes: 1

Related Questions