Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61832

How to decorate SwiftUI Views depending on condition?

This is what I mean:

var body: some View {
    Text(text)
        .font(Font.openSansLight(withSize: 15))
        .foregroundColor(Color(uiColor: mode.underlayTextColor))
    if scale { //this is a Bool value passed to initializer
        .scaledToFill() //Cannot infer contextual base in reference to member 'scaledToFill'
        .minimumScaleFactor(0.5)
        .lineLimit(1)
    }
}

Upvotes: 1

Views: 195

Answers (1)

Ashley Mills
Ashley Mills

Reputation: 53161

In the example above, you can use the ternary operator in the modifier parameter for .minimumScaleFactor and .lineLimit, e.g.

.minimumScaleFactor(scale ? 0.5 : 1)
.lineLimit(scale ? 1 : nil)

scaledToFill doesn't take a parameter, so you could create you're own modifier that does, e.g.

struct ScaledToFill: ViewModifier {
    
    let scale: Bool
    
    func body(content: Content) -> some View {
        if scale {
            content.scaledToFill()
        } else {
            content
        }
    }
}

extension View {
    func scaledToFill(_ scale: Bool) -> some View {
        modifier(ScaledToFill(scale: scale))
    }
}

then use it like:

.scaledToFill(scale)

Also see this for an example of a "conditional modifier" and why not to use it.

Upvotes: 3

Related Questions