代码之家  ›  专栏  ›  技术社区  ›  aheze But I'm Not A Wrapper Class

SwiftUI-双“”。clipped()`修饰符使视图消失

  •  1
  • aheze But I'm Not A Wrapper Class  · 技术社区  · 3 年前

    DotView ,由3个绿色圆圈组成 clipped DragGesture 在容器视图中水平滑动,该视图具有蓝色边框,并且 .

    我怎样才能防止它们消失? 有趣的是,如果我去掉第一个 剪裁 仅限剪辑 点视图 ,它们也不会消失。

    两个视图均已剪裁 只有 点视图
    Green circles disappear after sliding a bit
    绿色圆圈 消失
    Green circles stay, but overflow the red border
    绿色圆圈 .
    Green circles and red border both stay, but together they are not constrained to the blue border
    绿色圆圈 .

    这是我的代码:

    /// 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 circle disappears after nearing the edge

    不止一次,没有奇怪的副作用?为什么它们只在左侧消失而不在右侧? 或者也许, offset

    1 回复  |  直到 3 年前
        1
  •  2
  •   Asperi    3 年前

    看起来像是图形优化(是的,看起来像是由 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 }
            )
    }