[英]create a variable in a struct and access the variable in the same struct
I'm trying to add a custom font to a swift project and have a question for Swift's struct.我正在尝试向 swift 项目添加自定义字体,并对 Swift 的结构有疑问。 Since I'm gonna make custom fonts with different sizes and I need to use string ("My custom font") multiple times, I want to make a variable for the strings but get the error.
由于我要制作不同大小的自定义字体,并且需要多次使用字符串(“我的自定义字体”),因此我想为字符串创建一个变量,但出现错误。
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)
}
and I get this error message我收到此错误消息
Cannot use instance member 'myFont' within property initializer;
不能在属性初始值设定项中使用实例成员“myFont”; property initializers run before 'self' is available.
属性初始值设定项在 'self' 可用之前运行。
I want to call the font like Fonts.customFontNormal or something similar, but is there a way to make a string variable and enable to access the value from a variable in the same struct?我想调用字体,如 Fonts.customFontNormal 或类似的东西,但有没有办法制作字符串变量并允许从同一结构中的变量访问值?
Thanks to Jessy, I extend UIFont and add a new struct for the sting.感谢 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)!
}
}
Thanks a lot!非常感谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.