swift - 修复 navFont 不能用于类型 '...' 的实例?

标签 swift instance

我在使用 navFont 时遇到了一些问题。 在我的文件 CustomAppearance.swift 中,出现错误

navFont can't be used on instance of type 'Custom Appearance'.

这是我的代码:

import Foundation

struct CustomAppearance {

   static let navFont = UIFont(name: "SF-UI-Text-Light", size: 17.0)

   func applyCustomAppearanceToNavigationBar() {
       UINavigationBar.appearance().translucent = false
       UINavigationBar.appearance().barTintColor = UIColor.whiteColor()
       UINavigationBar.appearance().tintColor = UIColor.blackColor()
       UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: navFont!, NSForegroundColorAttributeName: UIColor.blackColor() ]
   }
}

最佳答案

您必须为静态变量使用限定名称:

struct CustomAppearance {

    static let navFont = UIFont(name: "SF-UI-Text-Light", size: 17.0)

    func applyCustomAppearanceToNavigationBar() {
        UINavigationBar.appearance().titleTextAttributes = [
            NSFontAttributeName: CustomAppearance.navFont!,
            NSForegroundColorAttributeName: UIColor.blackColor()
        ]
    }
}

在 Swift 的 future 版本中,语法 Self.navFont! 也将成为可能(参见 Swift Evolution - Universal Self )

关于swift - 修复 navFont 不能用于类型 '...' 的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36947747/

相关文章:

python - 如何以及在哪里计算 python 中的派生实例变量

swift - 如何在多行上进行正则表达式搜索?

swift - 从 Base64 格式解密 (Swift)

ios - AVAudioPlayer 实例的音量控制

java - Lookup 对象的实例

firebase - 如何减少 Firebase Cloud Firestore 上的读取操作?

python - 无法将对象附加到实例变量(列表)

objective-c - ios使用对象返回一个函数并使用它

ios - UIPickerView 更新速度慢

swift - 使用枚举快速存储当前状态类