UIViewRepresentable#
SwiftUI
尚未能實現,將 UIKit
中已有的部分進行封裝,提供給 SwiftUI
使用
UIViewRepresentable
協議提供了在 SwiftUI
中封裝 UIView
的功能
- 此協議需要實作2個方法
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
部件時被調用
例:在SwiftUI使用UIKit的UIVisualEffectView#
import SwiftUI
import UIKit
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.translatesAutorAutoresizingMaskIntoConstraints = false
view.addSubview(blurView)
NSLayoutConstraint.active([
blurView.heightAnchor.constraint(equal: view.heightAnchor),
blurView.widthAnchor.constraint(equal: view.widthAnchor)
])
return view
}
}