我刚刚发现 SwiftUI 的 UIViewRepresentable 有一些奇怪的行为。我不确定这是一个错误,还是我理解 SwiftUI 的错误。我做了小复制来显示问题。
我为 MKMapView 创建了 UIViewRepresentable:
import SwiftUI
import MapKit
struct UIMap: UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
let map = MKMapView(frame: .zero)
map.delegate = context.coordinator
return map
}
func updateUIView(_ map: MKMapView, context: Context) {
print("Change!")
}
func makeCoordinator() -> UIMapCoordinator {
return UIMapCoordinator(self)
}
class UIMapCoordinator: NSObject, MKMapViewDelegate {
var parent: UIMap
init(_ parent: UIMap) {
self.parent = parent
}
}
}
然后我为这个可表示的创建非常小的包装器:
import SwiftUI
struct MapWrapper: View {
var body: some View {
UIMap()
}
}
最后我在 ContentView 中使用它:
import SwiftUI
struct ContentView: View {
@State private var showSheet = false
@State private var showButton = true
var body: some View {
ZStack(alignment: .bottom){
MapWrapper()
HStack{
if showButton {
Button(action: { showSheet = true }){
Text("Show Sheet")
}
.foregroundColor(.yellow)
}
Spacer()
Button(action: { showButton = !showButton }){
Text("Toggle Button")
}
.foregroundColor(.yellow)
}
}
.sheet(isPresented: $showSheet) {
Text("Sheet content")
}
}
}
我在 ContentView 中有两个可点击元素 - 一个用于打开工作表,另一个用于隐藏按钮(只是为了查看状态更改)。打开工作表(更改showSheet
为true
)会导致updateUIView
被调用(“更改!”在调试控制台中打印),而更改showButton
不会这样做。看起来打开表改变了MapWrapper
(?)的状态。这种行为正确吗?