简体   繁体   English

NSForegroundColorAttributeName在Swift中不起作用?

[英]NSForegroundColorAttributeName doesn't work in Swift?

In viewDidLoad , I have something like the following to add text attributes to a UITextField : 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"

All of these attributes seem to work properly, except NSForegroundColorAttributeName . 除了NSForegroundColorAttributeName之外,所有这些属性似乎都能正常工作。 This text appears transparent. 此文字显得透明。 Is this a Swift bug? 这是一个Swift bug吗?

The text is being placed over an image in a UIScrollView . 文本被放置在UIScrollView的图像上。 Text as it appears: 出现的文字:

屏幕截图

From Technical Q&A QA1531 : 来自技术问答QA1531

This is because the sign of the value for NSStrokeWidthAttributeName is interpreted as a mode; 这是因为NSStrokeWidthAttributeName的值的符号被解释为模式; 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: 如果您在Xcode中按命令单击NSStrokeWidthAttributeName跳转到定义,也可以找到该信息:

NSNumber containing floating point value, in percent of font point size, default 0: no stroke; NSNumber包含浮点值,以字体点大小的百分比表示,默认为0:无笔画; positive for stroke alone, negative for stroke and fill (a typical value for outlined text would be 3.0) 单独使用中风,中风和填充为阴性(轮廓文本的典型值为3.0)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM