【问题标题】:SwiftUI on button tap call MKMapView.setRegionSwiftUI 上的按钮点击调用 MKMapView.setRegion
【发布时间】:2020-05-04 17:35:58
【问题描述】:

NavigationView 中,我有一个Button 和一个MKMapView(称为MapView)。当用户点击按钮时,地图应该会缩放到用户的位置。

我知道如何使用MKMapView.setRegion 缩放到用户的位置,但我不知道如何正确地让MapView 意识到它应该在用户点击按钮时执行此操作。

如果我以某种方式引用了我的 MapView 对象,我可以调用 setRegion,但我意识到这是必要的,现在当我学习 SwiftUI 时,我尝试以声明方式思考。

所以我认为我应该设置一个State 某种类型的变量,并让MapView 监听该变量的变化。但如果我能做到这一点,那么MapView 调用setRegion 无论如何都是必要的。

所以我在这里摸不着头脑。我该怎么办?

struct ContentView: View {

    @State private var foo: Bool = false

    var body: some View {
        NavigationView {
            MapView()
                .navigationBarItems(trailing:
                    HStack {
                        Button(action: {
                            // zoom to user's location
                            self.foo.toggle()
                        }) {
                            Image(systemName: "location")
                        }
                })
        }
    }
}

struct MapView: UIViewRepresentable {

    @Binding var foo: Bool

    // if foo is changed, then call zoomToUserLocation()

    func zoomToUserLocation() {
        // ...
        mapView.setRegion(region, animated: true)
    }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    不清楚你从哪里得到region(或者它被设置了),但是在任何这样的绑定上改变了可表示的updateUIView,所以会在那里进行调用并使其异步,如下所示

    func updateUIView(_ uiView: MKMapView, context: Context) {
        // if needed make something conditional here on `foo`
    
        self.zoomToUserLocation()
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 UIViewRepresentable 的 updateUIView 方法。我会这样使用:

      struct MapView: UIViewRepresentable {
      
          @Binding var foo: Bool
      
          func updateUIView(_ uiView: MKMapView, context: Context) {
      
              if foo {
                  self.zoomToUserLocation()
              }
      
          }
      
          func zoomToUserLocation() {
              // ...
              mapView.setRegion(region, animated: true)
          }
      }
      

      您也可以像 Asperi 所说的那样设置条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-06
        • 2022-01-03
        • 2021-03-21
        • 2014-09-15
        • 2019-12-11
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多