首页 > 解决方案 > SwiftUI 垂直 ScrollView 弹回并不显示其中的所有视图

问题描述

我正在开发一个布局与此类似的项目,其中我有几个视图堆叠在 VStack 中,底部有一个按钮,所有这些都嵌入在滚动视图中。正如您在图像中看到的那样,滚动视图会弹回并且不显示按钮。

在此处输入图像描述

var body: some View {
    VStack {
        Rectangle()
            .fill(Color.green)
            .frame(height: 300)
        Spacer()
        ScrollView {
            RectanglesView()
            Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                Text("Click me")
            }
            .offset(y: 50)
            .frame(width: 300)
            
        }
    }.edgesIgnoringSafeArea(.all)
}

我确实认为问题是由于按钮的偏移,因为如果我删除它,它会正常运行,但我不想丢失按钮的位置。

标签: iosswiftiphoneswiftuiscrollview

解决方案


代替偏移,添加填充,像这样在 VStack 中(下面稍微修改了代码)

    var body: some View {
    ZStack{
        VStack {
            Rectangle()
                .fill(Color.green)
                .frame(height: 300)
            Spacer()
            ScrollView {
                VStack{
                Rectangle()
                    .fill(Color.red)
                    .frame(height: 300)
                Rectangle()
                    .fill(Color.yellow)
                    .frame(height: 300)
                Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
                    Text("Click me")
                    }.padding() //instead of offset
                .frame(width: 300)
                }.frame(alignment: .leading)
                
            }
        }.edgesIgnoringSafeArea(.all)
    }
}

推荐阅读