【问题标题】:create a variable in a struct and access the variable in the same struct在结构中创建变量并访问同一结构中的变量
【发布时间】:2021-12-18 08:54:45
【问题描述】:

我正在尝试将自定义字体添加到 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 之类的字体或类似的字体,但有没有办法制作字符串变量并允许从同一结构中的变量访问值?

【问题讨论】:

  • 为什么你会使用static 来处理其中的一些,而不是全部?无关,类型是enum Font,而不是struct Fonts。但是为什么要创建一个类型而不是扩展 UIFont
  • 谢谢你,杰西。抱歉,我仍然是 Swift 的初学者,我只是按照 Sean Allen 的视频制作了自定义 UI。 youtu.be/C4f7R2gUO8E?t=279
  • 在视频中,他只为结构体做了一个字体标题,但这是我的误解。

标签: swift xcode struct


【解决方案1】:

感谢 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)!
    }
}

非常感谢!

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    相关资源
    最近更新 更多