swift - 在结构中创建变量并访问同一结构中的变量
问题描述
我正在尝试向 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 之类的字体或类似的字体,但是有没有办法制作一个字符串变量并允许从同一结构中的变量访问值?
解决方案
感谢 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)!
}
}
非常感谢!
推荐阅读
- laravel - Laravel 7 中重置密码的路径
- python - IndentationError: unindent 不匹配第 16 行文件 main.py 中的任何外部缩进级别
- reactjs - 基本形式反应
- angular - 如何在不使用集中式错误处理的情况下使用小吃吧在 Angular 8 中添加错误处理
- java - Spring Autowire byName,属性名称与 bean xml id 的名称不匹配
- java - 带有 kafka-clients-2.6.0 的 listTopics 给出 TimeoutException
- python - '(slice(None, None, None), 0)' 是无效键
- c - 为什么不复制所有非空格而不是 * 符号?为什么 strcpy 会修改源代码?
- excel - 代码在使用 F8 时有效,但在完全运行时无效
- scala - 遍历 Seq[row] 直到使用 Scala 满足特定条件