繁体   English   中英

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

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

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM