swift 如何在ZStack中合并视图以使顶视图优先?

pu3pd22g  于 5个月前  发布在  Swift
关注(0)|答案(1)|浏览(39)

我正在尝试重新创建Apple Maps UI,当一个工作表向上滑动时,该工作表与它下面的工作表合并 *,在那里仍然可以看到实际的Map,而不会降低不透明度。
基本上,我不希望工作表的背景变暗,因为更多的幻灯片上的对方。
视频:https://streamable.com/x3ugoa

struct ContentView: View {
    @State private var views: [Int] = []

    var body: some View {
        ZStack {
            LinearGradient(colors: [.red, .pink], startPoint: .top, endPoint: .bottom)
                .ignoresSafeArea()
            
            VStack {
                Button("Push View") {
                    withAnimation {
                        self.views.append(self.views.count + 1)
                    }
                }
                .foregroundStyle(.white)
                .padding()
                
                Button("Pop View") {
                    withAnimation {
                        if !self.views.isEmpty {
                            self.views.removeLast()
                        }
                    }
                }
                .foregroundStyle(.white)
                .padding()
                
                ZStack {
                    ForEach(0..<views.count, id: \.self) { index in
                        ZStack {
                            Rectangle()
                            Text("Rectangle \(index)")
                                .foregroundStyle(.white)
                        }
                        .shadow(radius: 5)
                        .foregroundStyle(.ultraThinMaterial)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .transition(.move(edge: .bottom))
                        .zIndex(Double(index))
                    }
                }
            }
        }
        .ignoresSafeArea(edges: .bottom)
    }
}

字符串

rqmkfv5c

rqmkfv5c1#

在“pushed”ZStack上使用一个简单的.opacity修饰符就可以了。
例如:

ForEach(0..<views.count, id: \.self) { index in
    ZStack {
        Rectangle()
        Text("Rectangle \(index)")
            .foregroundStyle(.white)
    }
    .shadow(radius: 5)
    .foregroundStyle(.ultraThinMaterial)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .transition(.move(edge: .bottom))
    .zIndex(Double(index))
    .opacity(index == views.count - 1 ? 1 : 0) //<- here
}

字符串
或者更简单的方法,有条件地显示视图

if index == views.count - 1 {
    ZStack {
        Rectangle()
        Text("Rectangle \(index)")
            .foregroundStyle(.white)
    }
    .shadow(radius: 5)
    .foregroundStyle(.ultraThinMaterial)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .transition(.asymmetric(insertion: .move(edge: .bottom), removal: .opacity))
    .zIndex(Double(index))
}


测试结果:


的数据

相关问题