当另一个视图处于活动状态时如何模糊背景? [英] How to blur background when another view is active?

查看:32
本文介绍了当另一个视图处于活动状态时如何模糊背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当第二个视图处于活动状态时,我尝试模糊第一个 VStack.但这样做时,启用模糊"每次点击按钮时,它的背景颜色都会改变.我不确定我哪里出错了,想知道是否有更好的方法来做到这一点.

I have tried blurring the first VStack when a view from the second one is active. 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)
            }
        }
    }
}

推荐答案

模糊效果的累积是因为 VStack 的内容没有被 SwiftUI 渲染引擎确定改变,所以它缓存的渲染变体用于下次重绘......等等.

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.

为了解决这个问题,我们需要将 VStack 标记为刷新.这是可能的解决方案.使用 Xcode 11.4/iOS 13.4 测试

To fix this we need to mark VStack to refresh. Here is possible solution. Tested with 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)

这篇关于当另一个视图处于活动状态时如何模糊背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆