在SwiftUI中访圃,有時候我們需要利用一些SwiftUI中不存在但是UIKit已有的View的時候柏靶,可以考慮使用包裝已有的UIView類型,然后提供給SwiftUI使用掸屡。
例如着憨,在SwiftUI中為View添加半透明的模糊效果墩衙。
SwiftUI中UIViewRepresentable協(xié)議提供了封裝UIView的功能。這個協(xié)議要求我們實現(xiàn)兩個方法:
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 在創(chuàng)建一個被封 裝的 UIView 時會對其調(diào)用。updateUIView(_:context:) 則在 UIViewRepresentable 中的某個屬性發(fā)生變化心铃,SwiftUI 要求更新該 UIKit 部件時被調(diào)用
創(chuàng)建一個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
}
}
}