不会发生在 for 循环 (UIKit) 中更改为 SwiftUI 状态变量

Change to SwiftUI state variable in for loop (UIKit) does not occur

所以我有一个 swift 视图,其中最小示例如下(它是一个 UIView,但为了简单起见,我将其设为 SwiftUI 视图):

class ViewName: UIView {

    
    @State var time: String = ""

    func setTime() {
        for place in self.data.places {
            print("the place address is \(place.address) and the representedobject title is \((representedObject.title)!!)")
            if (self.representedObject.title)!! == place.address {
                print("there was a match!")
                print("the time is \(place.time)")
                self.time = place.time
                print("THE TIME IS \(self.time)")
            }
        }
        print("the final time is \(self.time)")
    }

    var body: some View {
         //setTime() is called in the required init() function of the View, it's calling correctly, and I'm walking through my database correctly and when I print place.time, it prints the correct value, but it's the assignment self.time = place.time that just doesn't register. If I print place.time after that line, it is just the value ""
    }
}

引用类型不允许是 SwiftUI 视图。我们不能执行以下操作:

class ViewName: UIView, View {
  ...
}

,所以你的意思可能是这个

struct ViewName: View {

    // ... other properties

    @State var time: String = ""

    func setTime() {
        for place in self.data.places {
            if self.representedObject.title == place.address {
                self.time = place.time
            }
        }
    }

    var body: some View {
       Text("Some View Here")
         .onAppear {
            self.setTime()      // << here !!
         }
    }

}