所有的 container view (HStack, VStack, ZStack 等) 都有圖層的效應,後來的 view 的圖層都是高於前面的 view,所以如果有影子的話,會疊在前面的 view 身上。但在 container view 身上用 .compositingGroup() 就可以將所有圖層化為「同一圖層」。
import SwiftUI
typealias HA = HorizontalAlignment
typealias VA = VerticalAlignment
let w: CGFloat = 100
let h: CGFloat = 50
let r1 = Rectangle().padding(1).frame(w, h).foregroundColor(.pink)
let r2 = Rectangle().padding(1).frame(h, w).foregroundColor(.blue)
struct MyRects: View {
var body: some View {
ZStack {
r1
.alignmentGuide(HA.center) { $0[.leading] }
.alignmentGuide(VA.center) { $0[.bottom] }
r1
.alignmentGuide(HA.center) { $0[.trailing] }
.alignmentGuide(VA.center) { $0[.top] }
r2
.alignmentGuide(HA.center) { $0[.trailing] }
.alignmentGuide(VA.center) { $0[.bottom] }
r2
.alignmentGuide(HA.center) { $0[.leading] }
.alignmentGuide(VA.center) { $0[.top] }
}// VStack (container)
.aspectRatio(1, contentMode: .fit)
}
}
// live view
struct ContentView: View {
var body: some View {
HStack {
MyRects() // ⭐️ 不同圖層,影子會有層次感
MyRects()
.compositingGroup() // ⭐️ 變為同一圖層
}// HStack
.padding()
.shadow(color: .black, radius: 4, x: 4, y: 4)
.background(Color.gray)
}
}