0

I'm trying to add a custom font to a swift project and have a question for Swift's struct. 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; property initializers run before 'self' is available.

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?

3
  • Why would you use static for some of this, but not all? Unrelated, the type is enum Font, not struct Fonts. But why bother making a type instead of just extending UIFont? Commented Nov 4, 2021 at 3:19
  • Thank you Jessy. Sorry I'm still a beginner of Swift stuff and I just followed Sean Allen's video to make a custom UI. youtu.be/C4f7R2gUO8E?t=279 Commented Nov 4, 2021 at 3:25
  • In the video, he only makes a fonts title for the struct but that was my misunderstanding. Commented Nov 4, 2021 at 3:27

1 Answer 1

2

Thanks to Jessy, I extend UIFont and add a new struct for the 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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.