我无法找到诸如此类的后备方案
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 的东西。另外,如果你能改进这个 hack,那也很棒。
最佳答案
在 Swift 4 中你使用 UIFontDescriptor.AttributeName.xxx
和 NSAttributedStringKey.yyy where
xxx and
yyy` 是所需的名称。
在 Swift 3 中你使用 UIFontDescriptorXXXAttribute
和 NSYYYAttributeName
其中 XXX
和 YYY
是所需的名称。
只要您使用的 key 存在于 iOS 8 中,Swift 4 代码就可以像 iOS 11、10、9 和 8 一样正常工作。您不需要 #if
。或 #available
.
这意味着以下代码可以在 Xcode 9 中用于部署目标为 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
对于任何键。并且您应该注意对键字符串进行硬编码。使用提供的常量。
关于ios - Swift 中重命名属性的回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535574/