exyte / Grid

The most powerful Grid container missed in SwiftUI
MIT License
1.76k stars 93 forks source link

Need to explicitly assign height if it's conditionally rendered #7

Closed ghost closed 4 years ago

ghost commented 4 years ago

If the grid view is conditionally rendered, we have to manually assign its height.

Here is code snippets


// Use Grid in child view

struct RaceRunnerForm: View {
    @State private var isShownFullForm = false
    var body: some View {
        VStack(alignment: .leading, spacing: 5) {
            Text("Comments").bold()
            Divider()

            Grid(0..<formItemCount, tracks: 2, spacing: 10) { index in
                HStack(alignment:.center) {
                    Text("\(self.formLabelArray[index])")
                    Spacer()
                    Text(self.formDataArray[index])
                }
                .frame(height: 37)
            }.padding(.leading, -10).padding(.trailing, -10)
             .frame(height: 300) // have to assign height explictly
        }
    }
}

// Call from the parent view

@State private var isExpanded = false  // `Conditionally rendering`
var body: some View {
        VStack {
            HStack {
                VStack(spacing: 10) {
                VStack(alignment: .leading) {
                    Text(entrant.name).bold()
                }
            if isExpanded { 
                RaceRunnerForm()
            }
        }
    }
denis-obukhov commented 4 years ago

@golangnext How do you toggle the isExpanded value?

denis-obukhov commented 4 years ago

@golangnext Here are a similar code and video demo. Built with Xcode 11.5, run on iOS 13.5.1. Is it working as expected?

struct ConditionalExample: View {

    @State var isExpanded = false

    @ViewBuilder var raceRunnerForm: some View {
        VStack(alignment: .leading, spacing: 5) {
            Text("Comments").bold()
            Divider()

            Grid(0..<6, tracks: 2, spacing: 10) { index in
                HStack(alignment:.center) {
                    Text("Label")
                    Spacer()
                    Text("Data")
                }
                .frame(height: 37)
                .background(Color.red)
            }
            .padding(.leading, -10)
            .padding(.trailing, -10)
            .background(Color.yellow)
        }
    }

    @ViewBuilder
    var body: some View {
        VStack {
            Button(action: {
                self.isExpanded.toggle()
            }) {
                Text("Toggle")
            }
            HStack {
                VStack(spacing: 10) {
                    VStack(alignment: .leading) {
                        Text("Entrant name").bold()
                    }
                    if isExpanded {
                        self.raceRunnerForm
                    }
                }
            }
        }
    }
}
denis-obukhov commented 4 years ago

Any conditional rendering issues should be fixed in v0.0.3