【问题标题】:SwiftUI ScrollView vertical and horizontal scrollSwiftUI ScrollView 垂直和水平滚动
【发布时间】:2020-09-23 20:22:53
【问题描述】:

我有一个滚动视图,我想根据 @State 更改滚动的方向。

struct HomeScreen: View {
    @State var isVertical: Boolean = true

    var body: some View {
    VStack{
        Button(action: {
                self.isVertical.toggle()
            }) {
                Text("press me")
        }.padding()
        ScrollView(self.isVertical == true ? .horizontal : .vertical, showsIndicators: true){
                    if(self.isVertical){
                        HStack {
                            Text("a")
                            Text("b")
                            Text("c")
                            Text("d")

                            Spacer()
                        }
                    } else {
                        VStack{
                            Text("a")
                            Text("b")
                            Text("c")
                            Text("d")
                        }
                    }
                }.padding()
    }
}

当第一次在这个屏幕上滚动视图是垂直的时,只要我点击按钮并反转状态,滚动视图就会改变并变得疯狂,垂直和水平滚动。我究竟做错了什么?我希望基于您正在垂直或水平滚动的那个。非常感谢

【问题讨论】:

    标签: ios swift swiftui-list swiftui


    【解决方案1】:

    这里是固定的变体(也更正了isVertical 的处理以符合含义)

    使用 Xcode 11.4 / iOS 13.4 测试

    struct HomeScreen: View {
        @State var isVertical: Bool = true
    
        var body: some View {
            VStack{
                Button(action: {
                        self.isVertical.toggle()
                    }) {
                        Text("press me")
                }.padding()
                ScrollView(self.isVertical ? .vertical : .horizontal, showsIndicators: true){
                            if(self.isVertical){
                                VStack {
                                    Text("a")
                                    Text("b")
                                    Text("c")
                                    Text("d")
    
                                    Spacer()
                                }
                            } else {
                                HStack{
                                    Text("a")
                                    Text("b")
                                    Text("c")
                                    Text("d")
                                }
                            }
                        }.id(isVertical)       // << main part !!
                         .padding()
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2020-08-17
      • 2015-05-31
      • 2013-11-30
      相关资源
      最近更新 更多