【问题标题】:Swift 4 - Xcode 9 beta 4 - NSKernAttributeName vs NSAttributedStringKeySwift 4 - Xcode 9 beta 4 - NSKernAttributeName vs NSAttributedStringKey
【发布时间】:2017-08-03 00:02:56
【问题描述】:

iOS 部署目标:iOS 9.3, 基础 SDK:最新 iOS (iOS 11.0), Xcode 9 测试版 4, 斯威夫特 4

以下代码在 Swift 3、Xcode 8 中构建和运行:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSKernAttributeName] as? CGFloat ?? 0

但是,Swift 4 迁移器将其转换为:

    let kern = (CTRunGetAttributes(run) as? [String : Any])?
[NSAttributedStringKey.kern] as? CGFloat ?? 0

Xcode 9 现在抱怨:

Cannot subscript a value of type '[String : Any]' with an index of type 'NSAttributedStringKey'

根据检查员的说法,“NSAttributedStringKey”仅在 iOS 11 中可用。(请记住,我的目标是 iOS 9)。

如果我将“NSAttributedStringKey.kern”替换为“NSKernAttributeName”,错误仍然存​​在。

Command-clicking 'NSKernAttributeName' 告诉我它的可用性是 iOS 6。但是,检查器还声称它的类型是 'NSAttributedStringKey',它只在 iOS 11 中可用。我不知道这是否只是 API 演示的人工制品,或者是一个东西,或者我缺少的东西。

问题:我如何使用NSKernAttributeName(或其现代化版本)向后兼容iOS 9 和Swift 4?

感谢您的帮助。

【问题讨论】:

    标签: ios xcode swift4 xcode9-beta


    【解决方案1】:

    将字典键入为 [NSAttributedStringKey : Any] 而不是 [String : Any]。这都是 Swift 覆盖中的糖,所以它甚至可以在旧的 macOS/OS X 版本上工作。

    编辑:我应该澄清一下我的最后一句话。 NSAttributedStringKey,以及 Swift 4 中所有其他新的“Key”类型,只存在于 Swift 而不是 Objective-C。当带有 NSAttributedStringKey 键的字典桥接到 Objective-C 时,所有的键都会变成 NSString。由于您使用的实际 Foundation、UIKit 等框架是用 C/Objective-C 编写的,因此这将“正常工作”,您不必担心声称 NSAttributedStringKey 仅 10.11 的文档。

    【讨论】:

    • 谢谢你。非常感谢您的解释。
    【解决方案2】:
    textField.defaultTextAttributes[NSAttributedStringKey.kern.rawValue] = 16
    

    【讨论】:

      【解决方案3】:

      斯威夫特 4

      如果您不想忽略警告并进行强制转换,则可以将它们干净地复制到新字典中。

      var attributes: [NSAttributedStringKey: Any] = [:]
      textField.defaultTextAttributes.forEach{
          attributes[NSAttributedStringKey(rawValue: $0.key)] = $0.value
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-28
        • 1970-01-01
        • 2018-03-10
        • 1970-01-01
        • 2015-10-13
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多