SwiftUI 包裝UIView類(lèi)型

在SwiftUI中,有時(shí)候我們需要利用一些SwiftUI中不存在但是UIKit已有的View的時(shí)候,可以考慮使用包裝已有的UIView類(lèi)型,然后提供給SwiftUI使用。
例如,在SwiftUI中為View添加半透明的模糊效果。

SwiftUI中UIViewRepresentable協(xié)議提供了封裝UIView的功能。這個(gè)協(xié)議要求我們實(shí)現(xiàn)兩個(gè)方法:

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

makeUIView(context:) 需要返回想要封裝的 UIView 類(lèi)型,SwiftUI 在創(chuàng)建一個(gè)被封 裝的 UIView 時(shí)會(huì)對(duì)其調(diào)用。updateUIView(_:context:) 則在 UIViewRepresentable 中的某個(gè)屬性發(fā)生變化,SwiftUI 要求更新該 UIKit 部件時(shí)被調(diào)用

創(chuàng)建一個(gè)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
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容