Swift NSAttributedString:kCTForegroundColorAttributeName vs NSAttributedString.Key.foregoundColor
我有一个Swift NSAttributedString:kCTForegroundColorAttributeName vs NSAttributedString.Key.foregoundColor,swift,cocoa,appkit,nstextview,core-foundation,Swift,Cocoa,Appkit,Nstextview,Core Foundation,我有一个cfmutableAttributeString集合,其中属性为keykCTForegroundColorAttributeName,值为typeCGColor let attrString = NSMutableAttributedString(string: "foo bar") let range = CFRange(location:0, length:6) CFAttributedStringSetAttribute(attrString, range, k
cfmutableAttributeString
集合,其中属性为keykCTForegroundColorAttributeName
,值为typeCGColor
let attrString = NSMutableAttributedString(string: "foo bar")
let range = CFRange(location:0, length:6)
CFAttributedStringSetAttribute(attrString, range, kCTForegroundColorAttributeName, CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0))
我正在NSTextView的NSTextStorage上设置此字符串,但没有显示任何颜色
但是,对于相同的字符串,这样做是有效的-
// attrString is of type CFMutableAttributedString
let ret = NSMutableAttributedString(attributedString: attrString)
ret.addAttribute(.foregroundColor, value: NSColor.red, range: NSMakeRange(0, 10))
为什么使用核心基础属性名称的属性不起作用?使用核心基础API设置前景颜色的有效方法是什么,它将与NSTEXVIEW一起工作。
我使用的是Swift 5和OSX 10.15.2
为什么使用核心基础属性名称不工作的属性?< /P>
不是核心基础属性名称。它是一个核心文本属性名称,实际值为
CTForegroundColor
let attrString = NSMutableAttributedString(string: "foo bar")
let range = CFRange(location:0, length:6)
CFAttributedStringSetAttribute(attrString, range, kCTForegroundColorAttributeName, CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0))
文件明确指出:
属性由存储在CFDictionary
对象中的键/值对标识。键必须是CFString
对象,而相应的值是相应类型的CFType
对象有关macOS中的标准属性名称和iOS上的NSAttributedString UIKit Additions Reference,请参见NSAttributedString
Application Kit Additions Reference中的属性常量
您必须在此处使用AppKit框架常量。正确的是NSAttributedString.Key.foregroundColor
(实际值是NSColor
!=CTForegroundColor
)
let attrString=nsmutableAttributeString(字符串:“Hallo CoreFoundation!”)
let range=CFRange(位置:6,长度:14)
CFAttributedStringSetAttribute(属性字符串,
范围
NSAttributedString.Key.foregroundColor作为CFString,
红色);
label.attributedStringValue=attrString
除非您共享创建cfmutableAttributeString
的代码,kCTForegroundColorAttributeName
是“CTForegroundColor”
和NSForegroundColorAttributeName
是“NSColor”
。您是否尝试过CFMutableAttributedString
中的.foregroundColor
和NSColor.red
?无需尝试,它可以工作,请参阅:有关macOS中的标准属性名称,请参阅NSAttributedString应用程序工具包添加参考中的属性常量kCT
是核心文本框架中的一个常量。我在NSMutableAttributedString上调用了CFAttributedStringSetAttribute
更新了示例,但该调用无效。您是否阅读了我之前的评论和链接文档?它表示您必须对macOS中的属性名称使用NSAttributedString
AppKit addition reference=您必须将NSForegroundColorAttributeName
与CFMutableAttributedString
一起使用kCT
prefix是CoreText框架常量,而不是CoreFoundation框架。