Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSForegroundColorAttributeName doesn't work in Swift?

Tags:

swift

iphone

ios8

In viewDidLoad, I have something like the following to add text attributes to a UITextField:

let textAttributes = [
    NSForegroundColorAttributeName: UIColor.whiteColor(),
    NSStrokeColorAttributeName: UIColor.blackColor(),
    NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
    NSStrokeWidthAttributeName: 1.0
]

self.textField.delegate = self
self.textField.defaultTextAttributes = textAttributes
self.textField.text = "Top text field"

All of these attributes seem to work properly, except NSForegroundColorAttributeName. This text appears transparent. Is this a Swift bug?

The text is being placed over an image in a UIScrollView. Text as it appears:

Screen Shot

like image 959
Ja5onHoffman Avatar asked Jun 20 '15 14:06

Ja5onHoffman


1 Answers

From Technical Q&A QA1531:

This is because the sign of the value for NSStrokeWidthAttributeName is interpreted as a mode; it indicates whether the attributed string is to be filled, stroked, or both. Specifically, a zero value displays a fill only, while a positive value displays a stroke only. A negative value allows displaying both a fill and stroke.

So with your setting

NSStrokeWidthAttributeName: 1.0

the font is stroked only and not filled, resulting in an "outline font". You'll want to set

NSStrokeWidthAttributeName: -1.0

instead so that the font is stroked and filled.

You can find that information also if you command-click on NSStrokeWidthAttributeName in Xcode to jump to the definition:

NSNumber containing floating point value, in percent of font point size, default 0: no stroke; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0)

like image 174
Martin R Avatar answered Oct 23 '22 17:10

Martin R