UIViewRepresentable updateUIView() 使用 .sheet() 时的奇怪行为

问题描述

我刚刚发现 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(在调试控制台中打印“Change!”),而更改 showButton 不会这样做。看起来打开工作表更改了 MapWrapper(?) 的状态。这种行为是否正确?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)