内容更改时,SwiftUI ScrollView太小

时间:2020-06-04 18:26:16

标签: swift swiftui

此代码:


struct ContentView: View {

    @State var active: Bool = false

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            View2(active: self.$active).onTapGesture {
                self.active.toggle()
            }
        }
    }
}

struct View2: View {

    @Binding var active: Bool

    var body: some View {
        Group {

            ZStack {
                if self.active {
                    Rectangle().frame(width: UIScreen.main.bounds.width/1.2, height: 200).foregroundColor(Color.red)
                }

                Rectangle().frame(width: UIScreen.main.bounds.width/1.5, height: 100).foregroundColor(Color.yellow)
            }
        }
    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

然后按矩形。滚动视图似乎太小。现在,您可以水平移动矩形,也可以“滚动”矩形。您可以清楚地看到,它以看起来像第一个项目的宽度设置的边框切掉了新内容。

如何使边框/容器消失,以便在更改显示内容的大小时所有内容都可见,而只有垂直滚动?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

可能的解决方法

var body: some View {
    Group {

        ZStack {
            Rectangle().frame(width: UIScreen.main.bounds.width/1.2, height: 200)
                .foregroundColor(self.active ? .red : .clear)    // << here !!

            Rectangle().frame(width: UIScreen.main.bounds.width/1.5, height: 100).foregroundColor(Color.yellow)
        }
    }
}