Search code examples
swiftmacosnsattributedstringnsattributedstringkey

Error setting 'foregroundColor' in macOS


In a macOS project using Swift 3.2, I'm trying to set the foreground color of a UITextView.

let placeHolderTitleString: NSAttributedString = NSAttributedString(string: "Enter text here", attributes: [NSAttributedStringKey.foregroundColor : NSColor.gray]) // error

The error I get is this:

Type 'NSAttributedStringKey' (aka 'NSString') has no member 'foregroundColor'

The same code works fine in a Swift 4.0 project.

I'm trying to modify the code based on some answers I found for iOS Swift 4 Conversion error - NSAttributedStringKey: Any but I continue to get errors. Is there a way to fix this without to update the project to Swift 4?


Solution

  • Swift 3 doesn't use the new Swift 4 NSAttributeStringKey values.

    Use NSForegroundColorAttributeName for the foreground color:

    let placeHolderTitleString: NSAttributedString =
        NSAttributedString(string: "Enter text here", attributes:
        [NSForegroundColorAttributeName : NSColor.gray])