SwiftUI 包装UIView类型

在SwiftUI中,有时候我们需要利用一些SwiftUI中不存在但是UIKit已有的View的时候,可以考虑使用包装已有的UIView类型,然后提供给SwiftUI使用。
例如,在SwiftUI中为View添加半透明的模糊效果。

SwiftUI中UIViewRepresentable协议提供了封装UIView的功能。这个协议要求我们实现两个方法:

protocol UIViewRepresentable : View
    associatedtype UIViewType : UIView
    func makeUIView(context: Self.Context) !" Self.UIViewType
    func updateUIView(
        _ uiView: Self.UIViewType,
        context: Self.Context
    )
}

makeUIView(context:) 需要返回想要封装的 UIView 类型,SwiftUI 在创建一个被封 装的 UIView 时会对其调用。updateUIView(_:context:) 则在 UIViewRepresentable 中的某个属性发生变化,SwiftUI 要求更新该 UIKit 部件时被调用

创建一个BlurView

struct BlurView: UIViewRepresentable {

    let style: UIBlurEffect.Style

    func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView {
        let view = UIView(frame: .zero)
        view.backgroundColor = .clear

        let blurEffect = UIBlurEffect(style: style)
        let blurView = UIVisualEffectView(effect: blurEffect)

        blurView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(blurView)
        NSLayoutConstraint.activate([
            blurView.heightAnchor.constraint(equalTo: view.heightAnchor),
            blurView.widthAnchor.constraint(equalTo: view.widthAnchor)
        ])
        return view
    }

    func updateUIView(
        _ uiView: UIView,
        context: UIViewRepresentableContext<BlurView>)
    {
    }
}

extension View {
    func blurBackground(style: UIBlurEffect.Style) -> some View {
        ZStack {
            BlurView(style: style)
            self
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容