swift - 不会发生在 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 ""
}
}
解决方案
引用类型不允许是 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 !!
}
}
}
推荐阅读
- java - 如何使用 Jsoup 抓取 Youtube 视频的观看次数?
- html - 所有元素仍然具有 menuBar 样式?( )
- u-sql - Azure 数据工厂:如何将 U-SQL 变量导出到管道中的下一个框?
- javascript - javascript : 使用 eventlistener 和 debounce 延迟加载图像
- c# - 如何检测 WPF 中的窗口内容变化?
- sql-server - SQL如何比较变量是否与数据库列中的值相同?
- apache-kafka-connect - VoltDB 的连接器接收器是否支持 Avro 消息?
- django - Django 身份验证问题
- javascript - 在 eslint 中配置公共文件路径
- node.js - 为什么猫鼬中用户对象的属性显示为未定义?