UIAppearance Swift 4

17

升级到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 ... - Martin R
这是一个自定义的选项卡控制器类,我正在更改条目字体。 - Eli Whittle
你需要从UI类中调用,而不是直接从UIAppearance中调用。 - dimpiax
2
事实证明,当从Swift 3更新代码到Swift 4时,苹果的助手引入了错误的代码。 - Eli Whittle
你应该在 https://bugs.swift.org/ 上报告它,这样其他人就不必处理它了 :) - GetSwifty
同样的问题也出现在其他人身上。 - TheRealRonDez
1个回答

33

没错 - 当前的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等。 - Womble
你甚至可以省略NSAttributedStringKey,Swift可以推断它。 - rgkobashi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接