Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Conditional .frame View Modifier

I have my code as follows:

Rectangle()
    .fill(Color.red)
    .frame(width: 60, height: 60, alignment: .center)
    .cornerRadius(recording ? 5 : 30)

So I was wondering if .frame could be conditional just like .cornerRadius is. I am doing that in order to morph the shape, however I also need to make it smaller when it morphs. An example is a Voice Memos app's record button.

like image 954
EV3REST Avatar asked Sep 03 '25 16:09

EV3REST


1 Answers

If you're talking about using no frame modifier altogether (or providing a clean way to do different frames), a ViewModifier might be a good option:

struct ContentView: View {
    @State private var recording = false
    
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .modifier(CustomFrameModifier(active: recording))
            .cornerRadius(recording ? 5 : 30)
    }
}

struct CustomFrameModifier : ViewModifier {
    var active : Bool
    
    @ViewBuilder func body(content: Content) -> some View {
        if active {
            content.frame(width: 60, height: 60, alignment: .center)
        } else {
            content
        }
    }
}
like image 125
jnpdx Avatar answered Sep 05 '25 11:09

jnpdx