为什么在 UIViewRepresentable 的 updateUIView 方法中添加注释会导致我的 SwiftUI 应用程序出现动画卡顿?

问题描述 投票:0回答:1

我正在构建一个应用程序,当用户点击公交车图标时,仅在应用程序上添加公交车站注释。只要我在 updateUiView 方法中添加注释,我就会注意到视图动画中出现严重的卡顿。 一旦我删除它,应用程序就变得光滑如黄油。

我还可以在哪里调用此方法,以便当用户点击 swiftUI 中的公交车按钮时,仅将公交车注释添加到地图上?

func updateUIView(_ uiView: MKMapView, context: Context) {
        print("Updating MKMapView")

        if lastViewInStack == .nearbyBusStops {
            uiView.removeAnnotations(uiView.annotations) 
            
            //Adding annotations in updateUIView causes stuttering immediately...
            print("Adding annotations")
            uiView.addAnnotations(getLocations(center: uiView.centerCoordinate))
        } else {
            uiView.removeAnnotations(uiView.annotations)
        }

func getLocations(center: CLLocationCoordinate2D) -> [MKAnnotation] {
        var annotations = [MKAnnotation]()
        
        for busStop in nearbyBusStopsViewModel.nearbyBusStops {
            // Create an annotation
            let annotation = BusStopAnnotation(busStop: busStop)
            annotations.append(annotation)
        }
        
        return annotations
    }

class BusStopAnnotation: NSObject, MKAnnotation {
    let busStop: BusStop
    var coordinate: CLLocationCoordinate2D
    
    init(busStop: BusStop) {
        self.busStop = busStop
        self.coordinate = CLLocationCoordinate2D(latitude: busStop.wrappedLatitude, longitude: busStop.wrappedLongitude)
    }
}
swift swiftui mapkit mapkitannotation
1个回答
0
投票

updateUIView
的技巧是仅在您之前尚未添加注释时添加注释。将其视为差异。您可以使用
Coordinator
中的布尔值来完成此操作,或者如果没有太多的话,可以搜索地图的注释数组。

此外,您的

makeUIView
必须初始化并返回
MKMapView
的新实例,它也可以从
Coordinator
中初始化的
makeCoordinator
中的惰性属性返回它。

© www.soinside.com 2019 - 2024. All rights reserved.