Home > database >  Font weight as a parameter in SwiftUI
Font weight as a parameter in SwiftUI

Time:12-24

I am trying to pass font weight as a parameter to a component (SwiftUI View) to then use with Text. How can I do this?

I tried to set weight as Weight, UIFontDescriptor.TraitKey (found by searching), but neither work.

E.g.

let weight: Weight = .bold

init(weight: Weight){
    self.weight = weight
}

CodePudding user response:

There's a pretty quick way to figure out the type.

In a SwiftUI view write something like

Text("Hello").fontWeight(.bold)

Then ⌥-click on .bold and you'll see

enter image description here

CodePudding user response:

EDIT: use @vadian's solution!

As soon as I asked the question, I thought of a solution:

Pass the desired weight as a string, e.g. thin.

Then use a function when choosing the font:

.font(.system(size: 22, weight: getWeight(weight: weight), design: .rounded))
func getWeight(weight: String) -> Font.Weight {
    if weight == "thin" {
        return .thin
    }
    return .bold
}
  • Related