在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
}
}
}