如何在SwiftUI中禁用ScrollView剪辑内容

vpfxa7rd  于 2023-09-30  发布在  Swift
关注(0)|答案(4)|浏览(138)

我需要的红色矩形应该是可见的,直到达到该设备的领先或落后的边缘。所以问题是scrollview在移动到scrollview容器的大小之外时会剪切(隐藏)红框。验证码:

struct test: View {
var body: some View {
    ScrollView(.horizontal,showsIndicators:false) {
        LazyHStack{
            ForEach(0...4,id:\.self){i in
                Rectangle()
                    .fill(Color.red)
                    .frame(width: 60, height: 50, alignment: .center)
            }
        }.padding(.horizontal, 4)
    }.background(Color.yellow)
    .frame(width: 68, height: 60, alignment: .trailing)
}

}
结果:

预期:(我也通过设置ScrollView全宽并向LazyHStack添加填充(.padding(.horizontal, UIScreen.main.bounds.width/2 ))来产生此结果)但在开始和结束处添加空格是一种技巧,问题仍未解决,即ScrollView内容的裁剪

ttisahbt

ttisahbt1#

我不太确定问题出在哪里,但您可能希望padding位于Text上,而不是ScrollView上。纠正我,如果这不是你正在寻找的。

struct test: View {
    var body: some View {
        ScrollView(.horizontal) {
            Text("Hello, World!")
                .frame(width: UIScreen.main.bounds.width, alignment: .leading)
                .padding(.horizontal, 40)
        }
        .background(Color.yellow)
    }
}

测试结果:

ibps3vxo

ibps3vxo2#

在iOS 17中,现在ScrollView支持以下功能:

ScrollView {
   ...
}
.scrollClipDisabled()
hc2pp10m

hc2pp10m3#

当我删除这条线时,它似乎对我有效:.frame(width: UIScreen.main.bounds.width, alignment: .leading)
在iPhone XR上,我看到一个黄色背景的水平ScrollView,从前导40偏移开始,到尾随40偏移结束。这就是你想达到的目的吗
另外,我很确定UIScreen.main.bounds.width将返回设备的宽度,如果您希望文本占用比该值少80个像素,这将是一个问题(因为您的ScrollView两侧都有40个填充)。

hts6caw3

hts6caw34#

如果我对你的答案理解正确的话,这就是你想要的结果:

struct test: View {
    var body: some View {
         GeometryReader { geo in
             VStack {
                 Spacer()
                 HStack {
                     ScrollView(.horizontal,showsIndicators:false) {
                        LazyHStack{
                            ForEach(0...4,id:\.self){i in
                                Rectangle()
                                    .fill(Color.red)
                                    .frame(width: 60, height: 50, alignment: .center)
                            }
                        }
                        .padding(.horizontal,40)
                    }
                    .background(Color.yellow)
                    .frame(width: geo.size.width, height: 60, alignment: .center)
                 }
                 Spacer()
             }
        }
    }
}

结果:

相关问题