ios - Swift 中重命名属性的回退

标签 ios swift uikit swift4 xcode9

我无法找到诸如此类的后备方案

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.xxxNSAttributedStringKey.yyy where xxx and yyy` 是所需的名称。

在 Swift 3 中你使用 UIFontDescriptorXXXAttributeNSYYYAttributeName其中 XXXYYY是所需的名称。

只要您使用的 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/

相关文章:

iphone - UIActionSheet 上破坏性按钮的指南

ios - 自定义高度未应用于 UITableView 原型(prototype)单元格

ios - UITapGestureRecognizer 快速对 UIImageView 进行操作

javascript - 使用 evaluateJavaScript 从 WKWebView 获取标题

ios - Value of type 'QuerySnapshot' has no member 会出现 'data'错误

ios - 如何调整 UIScrollView 的大小以适应 UILabel 中未知数量的文本?

ios - 如何将 UITextField 中的文本垂直居中对齐?

iphone - 计算 UILabel 和 UIButtons 的大小来造句?

ios - 有什么方法可以使 UIAlertController 的所有按钮/操作中的文本变为粗体?

iphone - 将十进制数作为字符串输入 NSDecimalNumber 的简单方法?