使 SwiftUI 阴影不会在同级视图中流血

时间:2021-05-04 16:36:16

标签: swiftui

SwiftUI 阴影与其他内部兄弟视图重叠:

shadows overlapping

在这种情况下,有没有办法解决这个问题并获得适当的阴影?

示例视图:

// SwiftUIPlayground
// https://github.com/ralfebert/SwiftUIPlayground/

import SwiftUI

struct ShadowsView: View {
    var body: some View {
        Color.yellow
            .ignoresSafeArea()
            .overlay(self.scrollView, alignment: .bottom)
    }

    var scrollView: some View {
        VStack {
            ForEach(1 ... 3, id: \.self) { _ in
                Color.white
                    .frame(height: 100)
                    .cornerRadius(10)
                    .shadow(color: Color.red, radius: 30, x: 0, y: 0)
            }
        }
        .padding()
        .frame(height: 200, alignment: .top)
    }
}

1 个答案:

答案 0 :(得分:4)

您可以使用 .compositingGroup() 然后应用阴影。

documentation 声明:

<块引用>

合成组使此视图的祖先视图中的合成效果(例如不透明度和混合模式)在渲染此视图之前生效。

这意味着所有视图都与单独完成的阴影合成在一起,而不是阴影受到其下方视图的影响。

代码:

VStack {
    ForEach(1 ... 3, id: \.self) { _ in
        Color.white
            .frame(height: 100)
            .cornerRadius(10)
            // .shadow(color: Color.red, radius: 30, x: 0, y: 0)  // <- REMOVED
    }
}
.compositingGroup()  // <- ADDED
.shadow(color: Color.red, radius: 30, x: 0, y: 0)  // <- ADDED
.padding()
.frame(height: 200, alignment: .top)

结果:

Result

相关问题