我很难找到像这样的东西的备用方案
UIFontDescriptor.AttributeName
NSAttributedStringKey.foregroundColor这个问题出现在XCode 9中的Swift 4中。
#if swift(>=4.0)
if #available(iOS 11, *) {
[NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
} else {
["NSColor": UIColor.white]
}
#else
[NSForegroundColorAttributeName.rawValue: UIColor.white]但是,对于UIFontDescriptor,我找不到任何可以在iOS 8上工作的东西。另外,如果你能改进这个破解,那就太棒了。
发布于 2017-10-03 12:28:16
在Swift 4中,您使用UIFontDescriptor.AttributeName.xxx和NSAttributedStringKey.yyy wherexxxandyyy`是所需的名称。
在Swift 3中,您使用UIFontDescriptorXXXAttribute和NSYYYAttributeName,其中XXX和YYY是所需的名称。
只要您使用的密钥在iOS 8中存在,Swift 4代码就可以在iOS 11、10、9和8上正常工作。您不需要#if或#available。
这意味着以下代码可以在Xcode9中用于部署目标为iOS 8或更高版本的应用程序:
let fontDesc = UIFontDescriptor()
fontDesc.addingAttributes([ .name: "Helvetica" ])
let font = UIFont(descriptor: fontDesc, size: 14)
let dict = [ NSAttributedStringKey.foregroundColor: UIColor.green, NSAttributedStringKey.font: font ]
let attrStr = NSAttributedString(string: "Hello", attributes: dict)如果您需要同时使用Xcode 9和Xcode 8 (Swift 4和Swift 3)构建此代码,则需要执行以下操作:
let fontDesc = UIFontDescriptor()
#if swift(>=4.0)
fontDesc.addingAttributes([ .name: "Helvetica" ])
#else
fontDesc.addingAttributes([ UIFontDescriptorNameAttribute: "Helvetica" ])
#endif
let font = UIFont(descriptor: fontDesc, size: 14)
#if swift(>=4.0)
var dict = [ NSAttributedStringKey.foregroundColor: UIColor.yellow, NSAttributedStringKey.font: font ]
#else
var dict = [ NSForegroundColorAttributeName: UIColor.yellow, NSFontAttributeName: font ]
#endif
let attrStr = NSAttributedString(string: "Hello", attributes: dict)请注意,在这两组代码中,您都没有对任何键使用rawValue。而且你应该注意到对密钥串进行硬编码。使用提供的常量。
https://stackoverflow.com/questions/46535574
复制相似问题