Tom Fuller
Tom Fuller

Reputation: 73

SwiftUI drawingGroup() method seems to be bugged when its applied to a view that was build with a ForEach

In SwiftUI when using .drawingGroup() to flatten a View, I get different results than expected if the view builder uses a ForEach. Example code below results in a view that incorrectly shows only two Circles. If I comment out the .drawingGroup() call then the View correctly shows four Circles in a diamond formation.

Is there a way to get around this? When the .drawingGroup() works its seems pretty effective in improving memory performance and I would like to use if I can.

struct DrawingGroupView: View {
    var offsets = [CGPoint(x: 0, y: -1), CGPoint(x: -1, y: 0),
                   CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 1)]
    var width: CGFloat = 90
    var body: some View {
        ZStack {
            ForEach(0..<4) { index in
                Circle()
                    .offset(
                        x: offsets[index].x * width,
                        y: offsets[index].y * width
                    )
                    .frame(width: width)
            }
        }
        .drawingGroup()
    }
}

Upvotes: 3

Views: 917

Answers (1)

Asperi
Asperi

Reputation: 258345

The .offset modifier does not change layout of view, so width of your view remains equal to width of one circle, so flattening the view you see only two views got into container.

To solve this issue it appears the simplest is to make container screen-wide, like

    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)   // << here !!
    .drawingGroup()

Tested with Xcode 12.1 / iOS 14.1

demo

Upvotes: 2

Related Questions