ios - 如何设置 NSAttributedString 文本颜色?
问题描述
我试图将一些属性设置为 NSAttributedString。除前景色外,一切正常。
这就是我尝试设置属性的方式:
func setLabelText(text:String){
let strokeTextAttributes = [
NSAttributedString.Key.strokeColor : UIColor.white,
NSAttributedString.Key.foregroundColor : UIColor.red,
NSAttributedString.Key.font : UIFont.init(name: "Raleway-ExtraBold", size: 26)!,
NSAttributedString.Key.strokeWidth : 0.5,
]
as [NSAttributedString.Key : Any]
label.attributedText = NSMutableAttributedString(string: text, attributes: strokeTextAttributes)
}
正如您在图像中看到的那样,它没有设置文本颜色:
你知道为什么它会忽略foregroundColor 属性吗?
提前致谢。
解决方案
您的问题出在strokeWidth
属性上,因为您使用的是正数,只有笔画受到影响。您需要使用负数来更改笔触并填充文本,如strokeWidth属性的文档所述:
指定正值以单独更改笔划宽度。指定负值来描边和填充文本。
let strokeTextAttributes: [NSAttributedString.Key : Any] = [
.strokeColor : UIColor.white,
.foregroundColor : UIColor.red,
.font : UIFont.init(name: "Raleway-ExtraBold", size: 26)!,
.strokeWidth : -0.5,
]
在我看来,最好指定列表的数据类型,而不是将列表强制转换为该类型的特定类型。
推荐阅读
- javascript - Angular:如何获取页面内元素的滚动位置
- mysql - 仅当列名不为 Null 时选择
- arrays - 从对象中删除数组组件
- alexa - 使用 Alexa 搜索州和县
- android - 使用 Detox 在 React Native 中进行端到端测试 [不渲染资产和图像]
- django - 使用嵌套的外键序列化 ManyToManyField
- clickatell - 收到消息“消息传递状态ERROR_DELIVERING”,有没有办法自动重新发送短信?
- angular - 从Typescript angular中的json对象获取数组
- generics - Kotlin 将泛型类转换为 Unit
- html - 多个相同大小的 SVG 元素在 DOM 上显示不同的大小