简体   繁体   English

当另一个视图处于活动状态时如何模糊背景?

[英]How to blur background when another view is active?

I have tried blurring the first VStack when a view from the second one is active.当第二个视图处于活动状态时,我尝试模糊第一个 VStack。 But when doing so, the "Enable Blur" Button's background colour changes every time it is tapped.但是这样做时,每次点击“启用模糊”按钮的背景颜色都会改变。 I am not sure where I'm going wrong here and would like to know if there's a better way to do this.我不确定我在哪里出错了,想知道是否有更好的方法来做到这一点。

struct ContentView: View {
    
    @State private var showWindow = false
    var body: some View {
        ZStack{
            VStack{
                Button(action: {self.showWindow.toggle()}){
                    Text("Enable Blur")
                        .foregroundColor(.white)
                        .padding()
                        .background(Color.black)
                        .cornerRadius(5)
                }
            }.blur(radius: showWindow ? 5 : 0)
            VStack{
                if(showWindow){
                    DatePickerView(showWindow: self.$showWindow)
                }
            }
        }
    }
}

struct DatePickerView: View {
    @Binding var showWindow: Bool
    var body: some View{
        VStack{
            Button(action: {self.showWindow.toggle()}){
                Text("Done").foregroundColor(.white)
            }
        }
    }
}

The blur effect accumulates because VStack content is not determined as changed by SwiftUI rendering engine, so its cached rendered variant is used to next redraw.. and so on.模糊效果累积是因为 SwiftUI 渲染引擎未确定 VStack 内容已更改,因此其缓存的渲染变体用于下一次重绘..等等。

To fix this we need to mark VStack to refresh.为了解决这个问题,我们需要将 VStack 标记为刷新。 Here is possible solution.这是可能的解决方案。 Tested with Xcode 11.4 / iOS 13.4使用 Xcode 11.4 / iOS 13.4 测试

VStack{
    Button(action: {self.showWindow.toggle()}){
        Text("Enable Blur")
            .foregroundColor(.white)
            .padding()
            .background(Color.black)
            .cornerRadius(5)
    }
}.id(showWindow)                  // << here !!
.blur(radius: showWindow ? 5 : 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM