SwiftUI,无法从委托回调中更改状态? (附代码)

SwiftUI, can't change state from within delegate callback? (code attached)

有人能发现为什么当我在“updateUIView”回调中设置“firstPass”状态变量时它没有设置状态吗?作为输出,我看到:

First Pass1:  true
First Pass2:  true. // <= not set to false as expected

此外,我没有在 Xcode 中设置此状态“firstPass = false”,这里有一个 Xcode 警告:“在视图更新期间修改状态,这将导致未定义的行为。 “

import SwiftUI
import MapKit

struct GCMapView {
    @State var firstPass : Bool = true
   
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }
    class Coordinator: NSObject, MKMapViewDelegate {
        var parent: GCMapView
        init(_ parent: GCMapView) {
            self.parent = parent
            super.init()
        }
    }
}

extension GCMapView : UIViewRepresentable {
    func makeUIView(context: Context) -> MKMapView {
        let map = MKMapView()
        map.delegate = context.coordinator
        map.showsUserLocation = true
        return map
    }

    func updateUIView(_ view: MKMapView, context: Context) {
        print("--- updateUIView ---")
        if firstPass {
            print("First Pass1: ", firstPass)
            firstPass = false.      // <<=== *** THIS DOES NOT WORK ****
            print("First Pass2: ", firstPass)
        } else {
            print("Subsequent Passes")
        }
    }
}

此操作会导致循环,因为它会使导致调用 updateUIView 等的 SwiftUI 视图无效,因此 SwiftUI 渲染引擎会丢弃它(自动修复)。

不太确定你是否需要这样的if,但可能的解决方案是在下一个事件循环中单独更新,比如

if firstPass {
    print("First Pass1: ", firstPass)
    DispatchQueue.main.async {
       firstPass = false
       print("First Pass2: ", firstPass)
    }
} else {

测试 Xcode 13 / iOS 15