【问题标题】:Custom MapAnnotation leads to "[SwiftUI] Publishing changes from within view updates is not allowed, this will cause undefined behavior"自定义 MapAnnotation 导致“[SwiftUI] 不允许从视图更新中发布更改,这将导致未定义的行为”
【发布时间】:2022-10-24 21:02:58
【问题描述】:

如果我使用默认的MapMarker,地图可以正常工作。但是,如果我使用简单的自定义MapAnnotation,地图会变得非常缓慢,并且当我在地图上移动时会无数次显示错误信息。

[SwiftUI] 不允许从视图更新中发布更改,这将导致未定义的行为”

我的代码如下:

struct UNESCOUIView: View {
    
    @EnvironmentObject private var UM: UNESCOModel
    @State var isShowingMapView = false
 
    var body: some View {

        NavigationView {
           //code
        }
        .sheet(isPresented: $isShowingMapView) {
            MapUNUIView(UNsites: $UM.UNESCOSites, isShowingMapView: $isShowingMapView)
        }
    }



struct MapUNUIView: View {
    
    @Binding var UNsites:[UNESCOSite]
    @Binding var isShowingMapView: Bool
    
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10))
    

    var body: some View {
        
        NavigationView {
            Map(coordinateRegion: $region, showsUserLocation: true, annotationItems: $UNsites) { $place in
                 // works fine with this
                //MapMarker(coordinate: place.coordinate)

                // doesn't work with this
                MapAnnotation(coordinate:  place.coordinate) {
                Circle()
                 .strokeBorder(.red, lineWidth: 4)
                 .frame(width: 40, height: 40)
           }
        }.ignoresSafeArea(.all)

        }
    }

【问题讨论】:

    标签: swift swiftui mapkit


    【解决方案1】:

    我也遇到了这个问题,似乎是这样解决了它(我真的不明白为什么,所以如果有人能解释它为什么起作用以及为什么以前的做法现在不那么感激)

    我对此不以为然,因为这是另一个名为tonyayoubApple developer forums 上的用户提供的解决方案

    这就是他发现的,产生警告的代码是:

    struct AreaMap: View {
    
      @Binding var region: MKCoordinateRegion
    
      var body: some View {
        Map(coordinateRegion: $region)
      }
    }
    

    区域从其父视图在 AreaMap 的初始化程序中传递的位置。 这解决了这个问题:

    struct AreaMap: View {
    
      @Binding var region: MKCoordinateRegion
    
      var body: some View {
        let binding = Binding(
          get: { self.region },
          set: { newValue in
            DispatchQueue.main.async {
              self.region = newValue
            }
          }
        )
        return Map(coordinateRegion: binding)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 2023-02-01
      • 2021-09-17
      • 2023-02-06
      • 2022-10-04
      • 2020-03-11
      • 2020-05-15
      • 2021-01-10
      • 2020-10-27
      相关资源
      最近更新 更多