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