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

时间:2020-08-29 15:44:40

标签: swift for-loop uiview 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 ""
    }
}

1 个答案:

答案 0 :(得分:1)

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

class ViewName: UIView, View {
  ...
}

demo

,所以你可能是这个意思

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 !!
         }
    }

}