首页 > 解决方案 > 为自定义控件复制用于 SwiftUI GraphicalDatePickerStyle 的背景模糊

问题描述

我正在尝试开发一个自定义控件,以在与 SwiftUI 的 DatePicker 类似的表单中使用(在默认为 GraphicalDatePickerStyle 的表单中)。

Apple 的控件以模态方式显示日历和时间选择器,背景模糊。我可以使用 .fullScreenCover 修饰符来管理模态演示。通过将 UIVisualEffectView 添加到显示控件的背景也可以实现背景模糊。但是,即使使用系统默认提供的最轻的选项,以这种方式应用的模糊也过于笨拙。我也对通过 DispatchQueue.main.async 修改超级视图背景的依赖感到不满——它有效,但让我感到不舒服。

有没有办法接近苹果的实施?我尝试添加一个活力效果层并没有让我到任何地方,根据文档,你不应该触摸 UIEffectViews 的 alpha ......

下面的视觉效果的代码和比较(期望的和当前的迭代):

import SwiftUI

struct ContentView: View {
    @State private var isPresented = false
    @State private var interval: TimeInterval = 0
    
    var body: some View {
        Form {
            Text("Row")
            Text("Row")
            Text("Row")
            Text("Row")
            
            DatePicker("Date", selection: .constant(Date()))
            
            Button("Present custom control") {
                self.isPresented.toggle()
            }
            .fullScreenCover(isPresented: $isPresented) {
                ZStack {
                    Color.white.opacity(0.1)
                        .edgesIgnoringSafeArea(.all)
                    // below is a placeholder for the custom control
                    Button("Dismiss") { isPresented.toggle() }
                        .frame(width: 200, height: 200)
                        .background(Color.white)
                        .cornerRadius(16)
                }
                .background(BackgroundBlurView())
            }
            
            Text("Other stuff here")
                .background(Color.red)
        }
    }
}

struct BackgroundBlurView: UIViewRepresentable {
    func makeUIView(context: Context) -> UIView {
        let view = UIVisualEffectView(effect: UIBlurEffect(style: .systemUltraThinMaterial))
        // this works but it looks a bit hacky... code smell?
        DispatchQueue.main.async {
            view.superview?.superview?.backgroundColor = .clear
        }
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // nothing needed here
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
        }
    }
}

表格(在控制点击之前) 表格(在控制点击之前)

DatePicker 应用的背景模糊 DatePicker 应用的背景模糊

我的尝试 - 不远程关闭! 当前尝试 - 明显模糊和失去活力

标签: iosswiftformscontrols

解决方案


推荐阅读