0

I have the following view:

struct ChordPadView: View {
    [...]

    init() {
        [...]
    }

    var body: some View {
        [...]

        if globalState.interfaceMode == .Normal {
            HStack {
             [...]

              SomeView(playChord, stopChord) {
                  VStack {
                      Text(showType ? "\(chord.note)\(chord.type)" : chord.note)
                          .font(Font.custom("AeroMaticsBold", size: 15))

                      if (!self.hideNumeral) {
                          Text(self.numeral ?? chord.numeral ?? "")
                              .font(Font.custom("AeroMaticsBold", size: 8))
                      }
                  }
              }
            }
        } else {
            SomeOtherView(playChord, stopChord) {
                VStack {
                    Text(showType ? "\(chord.note)\(chord.type)" : chord.note)
                        .font(Font.custom("AeroMaticsBold", size: 15))

                    if (!self.hideNumeral) {
                        Text(self.numeral ?? chord.numeral ?? "")
                            .font(Font.custom("AeroMaticsBold", size: 8))
                    }
                }
            }
        }
    }
}

Basically, I have two very different view, SomeOtherView and SomeOtherView and within the logic of my view I need to pass to either one or the other the very same block of content.

How can I refactor my code in order to avoid the duplication and stay DRY? Is there a way to assign the VStack block to a variable to use it in multiple places?

0

1 Answer 1

1

Create a custom view for the VStack. Either use it directly in the if-else statement, or pass it to ChordPadView.

struct ChordPadView: View {
    var body: some View {
        if (true) {
            HStack {
                VStackView()
            }
        } else {
            VStackView()
        }
    }
}

Or

struct ChordPadView<Content: View>: View {
    var content: Content
    
    init(content: Content) {
        self.content = content
    }
    
    var body: some View {
        if (true) {
            HStack {
                VStackView()
            }
        } else {
            VStackView()
        }
    }

}


struct VStackView: View {
    var body: some View {
        VStack{
            Text("VStack View")
        }
    }
}

The else statment is never executed since the condition is always true.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.