🌅BlurView

可以讓在它下面的 view 變模糊。


import SwiftUI

// 🌅 BlurView
public struct BlurView: UIViewRepresentable {
    
    public typealias UIViewType = UIView
    let style: UIBlurEffect.Style
    
    public init(_ style: UIBlurEffect.Style = .systemMaterial) {
        self.style = style
    }
    
    public func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView {
        
        // view (parent view)
        let view = UIView(frame: CGRect.zero)
        view.backgroundColor = .clear
        
        // ⭐️ blur effect
        let blurEffect = UIBlurEffect(style: style)
        // ⭐️ blur view (subview)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.translatesAutoresizingMaskIntoConstraints = false  // auto layout
        view.insertSubview(blurView, at: 0)
        // ⭐️ blurView.size == view.size
        NSLayoutConstraint.activate([
            blurView.widthAnchor.constraint(equalTo: view.widthAnchor),
            blurView.heightAnchor.constraint(equalTo: view.heightAnchor),
        ])
        
        return view
    }
    
    public func updateUIView(
        _ uiView: UIView, 
        context : UIViewRepresentableContext<BlurView>
    ) { }
}

Last updated