【问题标题】:Sizing multiple vstack width in scroll view, SwiftUI在滚动视图中调整多个 vstack 宽度,SwiftUI
【发布时间】:2020-10-06 18:48:46
【问题描述】:

我有一个VStack

VStack(alignment: .leading) {
        Text(question)
            .fontWeight(.heavy)
            .font(.system(.footnote, design: .rounded))
            .padding(.bottom)
        Text(answer)
            .fontWeight(.semibold)
            .font(.system(.title, design: .rounded))
    }
    .padding(35)
    .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color("darkGrey"), lineWidth: 2))
    .padding([.leading,.top,.trailing])
    .frame(minWidth: UIScreen.main.bounds.width - 5,
           minHeight: 50,
           maxHeight: .infinity,
           alignment: .topLeading
    )

我在我的View 中使用它,例如:

ScrollView(.horizontal, showsIndicators: false) {
                Group {
                    HStack {
                        questionCard(question: "Cats or Dogs", answer: "Dogs")
                        questionCard(question: "Cats or Dogs", answer: "Dogs")
                    }
                }
            }

这会导致以下结果:

我试图将框的width 移到屏幕的末尾(带有.trailing 空格),然后当我滚动到下一个时,它应该是相同的宽度。

【问题讨论】:

    标签: swift swiftui vstack hstack


    【解决方案1】:

    您可以执行以下操作:

    struct ContentView: View {
        var body: some View {
            ScrollView(.horizontal, showsIndicators: false) {
                Group {
                    HStack {
                        QuestionCard(question: "Cats or Dogs", answer: "Dogs")
                        QuestionCard(question: "Cats or Dogs", answer: "Dogs")
                    }
                }
            }
        }
    }
    
    struct QuestionCard: View {
        let question: String
        let answer: String
        
        var body: some View {
            
            HStack {
                Spacer()
                VStack(alignment: .leading) {//<- Change the alignment if needed
                    Text(question)
                        .fontWeight(.heavy)
                        .font(.system(.footnote, design: .rounded))
                        .padding(.bottom)
                    Text(answer)
                        .fontWeight(.semibold)
                        .font(.system(.title, design: .rounded))
                }
                Spacer()
                
            }
            .padding(35)
            .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.black, lineWidth: 2))
            .padding([.leading, .top, .trailing])
            .frame(minWidth: UIScreen.main.bounds.width - 5,
                   minHeight: 50,
                   maxHeight: .infinity,
                   alignment: .top
            )
        }
    }
    

    所以基本上我只是使用一个HStack 和两个Spacers 来使用所有可用空间。 它看起来像这样:

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 2019-10-22
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      相关资源
      最近更新 更多