【问题标题】:UIAppearance Swift 4UIAppearance Swift 4
【发布时间】:2017-07-17 17:40:28
【问题描述】:

更新到 Swift 4 后,出现编译器错误:

Static member 'appearance' cannot be used on protocol metatype 'UIAppearance.Protocol'

这是我的自定义标签栏控制器子类中的viewWillAppear 方法,我正在设置项目文本的字体。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // compiler error on line below
    UIAppearance.appearance().setTitleTextAttributes([NSAttributedStringKey.font: font], for: UIControlState.normal)
}

我在解决这个问题时遇到了问题,我们将不胜感激,谢谢!

【问题讨论】:

  • 该代码应该做什么?通常外观是为具体的 UI 类设置的,例如UIBarItem.appearance().setTitleTextAttributes ...
  • 我将在问题中提供更多上下文。这是一个自定义标签栏控制器类,我正在更改栏项目的字体。
  • 你需要从 UI 类调用,而不是直接从 UIAppearance 调用。
  • 原来,在将代码从 Swift 3 更新到 Swift 4 时,Apple 的 helper 引入了错误的代码。
  • 您应该在bugs.swift.org 报告它,这样其他人就不必处理它了:)

标签: ios swift uiappearance xcode9-beta swift4


【解决方案1】:

没错 - 当前的 Swift 4 转换工具(从 Xcode 9 Beta 4 开始)有点过时了。

通过还原UIAppearance 转换代码,然后更新各个属性,我能够快速解决问题。

例如,在 Swift 3 中,我有:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.white], for: .selected)

Xcode “帮助”了我,将其更改为:

UIAppearance.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .selected)

我能够通过半还原来消除错误:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .selected)

【讨论】:

  • 这里也一样。迁移器将类型更改为 UIAppearance,而不是 UITabBarItem、UIImageView 等。
  • 你甚至可以省略 NSAttributedStringKey,swift 可以推断出来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多