2

我有一个视图,DotView它由 3 个绿色圆圈clipped和一个红色边框组成。我DragGesture用来在容器视图中水平滑动它,它有一个蓝色边框,也是clipped.

问题是,一旦我滑到某个点,3 个绿色圆圈就会消失。我怎样才能防止它们消失?有趣的是,如果我删除第一个clipped也是唯一一个剪辑蓝色容器,圆圈不会消失。同样,如果我删除第二个clipped也是唯一一个 clip DotView,它们也不会消失。

两个视图都被剪裁了 仅裁剪蓝色视图 DotView剪裁
滑动一点后绿色圆圈消失
绿色圆圈消失
绿色圆圈停留,但溢出红色边框
绿色圆圈停留
绿色圆圈和红色边框都保留,但它们一起不受蓝色边框的限制
绿色圆圈停留

这是我的代码:

/// 3 green circles, constrained to a red border
struct DotView: View {
    var body: some View {
        HStack {
            ForEach(0..<3) { _ in
                Circle()
                    .fill(Color.green)
                    .frame(width: 100, height: 100)
            }
        }
        .frame(width: 250)
        .border(Color.red)
        .clipped() /// 1. make sure the green circles don't overflow
    }
}

/// container for horizontal dragging, with a blue border
struct ContentView: View {
    @State var offset = CGFloat(0)
    var body: some View {
        DotView()
            .padding() /// add a small gap between the red and blue borders
            .offset(x: offset, y: 0)
            .border(Color.blue)
            .clipped() /// 2. make sure `DotView` doesn't overflow the blue border
            .gesture(
                DragGesture(minimumDistance: 0) /// slide `DotView` left and right
                        .onChanged { offset = $0.translation.width }
            )
    }
}

消失效果在 中非常明显ForEach,但在其他视图中也会出现。例如,当您将整个替换为 时会发生以下HStack情况Circle().fill(Color.green).frame(width: 100, height: 100)

1个圆圈在接近边缘后消失

有什么方法可以让我使用clipped不止一次,而不会产生奇怪的副作用?为什么它们只消失在左侧而不是右侧?或者,offset是什么导致了问题?

4

1 回答 1

2

看起来像绘图优化(是的,看起来它起源于offset)。

无论如何,这是一个修复 - 使用绘图组来修复内容(使用 Xcode 13 / iOS 15 测试):

var body: some View {
    DotView()
        .padding()
        .drawingGroup()               // << here !!
        .offset(x: offset, y: 0)
        .border(Color.blue)
        .clipped()
        .gesture(
            DragGesture(minimumDistance: 0) /// slide `DotView` left and right
                .onChanged { offset = $0.translation.width }
        )
}
于 2021-11-20T05:29:58.617 回答