首页 > 解决方案 > 在结构中创建变量并访问同一结构中的变量

问题描述

我正在尝试向 swift 项目添加自定义字体,并对 Swift 的结构有疑问。由于我要制作不同大小的自定义字体并且我需要多次使用字符串(“我的自定义字体”),我想为字符串创建一个变量但得到错误。

struct Fonts {

    let myFont = "My custom font"
    let myFontBold = "My custom font bold"

    static let customFontNormal = UIFont(name: self.myFont, size: 16.0)
    static let customFontBold = UIFont(name: self.myFontBold, size: 16.0)
}

我收到此错误消息

不能在属性初始化程序中使用实例成员“myFont”;属性初始化程序在 'self' 可用之前运行。

我想调用 Fonts.customFontNormal 之类的字体或类似的字体,但是有没有办法制作一个字符串变量并允许从同一结构中的变量访问值?

标签: swiftxcodestruct

解决方案


感谢 Jessy,我扩展了 UIFont 并为 sting 添加了一个新结构。

struct Fonts {

    static let myFont = "myFont"
    static let myFontBold = "myFontBold"
}


extension UIFont {

    static func myFontNormal() -> UIFont {
        return UIFont(name: Fonts.myFont, size: 16)!
    }

    static func myFontBoldNormal() -> UIFont {
        return UIFont(name: Fonts.myFontBold, size: 16)!
    }
}

非常感谢!


推荐阅读