首页 > 解决方案 > 不会发生在 for 循环 (UIKit) 中对 SwiftUI 状态变量的更改

问题描述

所以我有一个快速的视图,最小的例子如下(它是一个 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 ""
    }
}

标签: swiftfor-loopuiviewswiftui

解决方案


引用类型不允许是 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 !!
         }
    }

}

推荐阅读