NSForegroundColorAttributeName 在 Swift 中不起作用?

NSForegroundColorAttributeName doesn't work in Swift?

viewDidLoad 中,我有类似下面的东西来将文本属性添加到 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"

所有这些属性似乎都可以正常工作,但 NSForegroundColorAttributeName 除外。此文本显示透明。这是 Swift 错误吗?

文本被放置在 UIScrollView 中的图像上。显示的文本:

您需要使用文本属性创建一个 NSAttributedString,然后设置文本字段的 attributedText 属性:

textField.attributedText = NSAttributedString(string: "Top text field", attributes: textAttributes)

来自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.

所以根据你的设置

NSStrokeWidthAttributeName: 1.0

字体仅描边,未填充,结果为 "outline font"。您需要设置

NSStrokeWidthAttributeName: -1.0

而不是让字体被描边填充。

如果您按住命令并单击,您也可以找到该信息 NSStrokeWidthAttributeName in Xcode 跳转到定义:

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)