【问题标题】:How do I add ".setRegion" in updateUIView in SwiftUI MapKit?如何在 SwiftUI MapKit 的 updateUIView 中添加“.setRegion”?
【发布时间】:2020-09-16 21:21:50
【问题描述】:

我需要在 SwiftUI 中使用 MapKit。以前我使用的是故事板。在调用“updateUIView”函数使用 MapKit 后,我​​无法执行“uiView.setRegion”。我该如何解决这个问题?

func updateUIView(_ uiView: UIViewType, context: Context) {
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.setRegion(region, animated: true)
    }

我收到此错误消息:“某些 UIView”类型的值没有成员“setRegion”

【问题讨论】:

  • 你的 UIViewType 应该是 MKMapView,但我认为它不应该在 updateUIView 中,在 makeUIView 中进行。

标签: swift xcode swiftui


【解决方案1】:

请将func updateUIView(_ uiView: UIViewType, context: Context) 更新为func updateUIView(_ uiView: MKMapView, context: Context)

为了让updateUIView 接收uiView: as MKMapView,您必须在makeUIView 函数中返回 MKMapView,所以像这样 func makeUIView(context: Context) -> MKMapView

struct MapView: UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }
    
    func updateUIView(_ uiView: MKMapView, context: Context) {

        let span = MKCoordinateSpan(latitudeDelta: 2.0,
                                    longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate,
                                        span: span)
        uiView.setRegion(region,animated: true)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多