ios - Reload data but the ObservableObject is not working
问题描述
With SwiftUI, I'm trying to update the data when I create a Favorite
object in the database. It is created successfully, and when I call the functions reload, it can get the correct information.
However, when I change the View, it is not reloaded in the View.
MY DATA CODE:
// Favorite
struct Favorite: Decodable, Identifiable {
var id:Int?
public var id: Int?
public var name: String?
public var type: String?
var addres: String?
}
class Favorite: ObservableObject {
var userID = userViews().id
@Published var favorites = [Favorite]()
init(){
load()
}
func load() {
let url = URL(string: "https://***********/getFavoriteApi/")
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode([Favorite].self, from: d)
DispatchQueue.main.async {
self.favorites= decodedLists
print(self.favorites)
}
}else {
print("No Data")
}
} catch {
print ("Error")
}
}.resume()
}
}
If I print(self.favorites) it can see the new Optional after create Favorite, but view is not reload it.
MY VIEW CODE:
struct FavoriteView: View {
@ObservedObject var favorites = Favorite()
var name = UserDefaults.standard.value(forKey: "name")as? String ?? "null"
var userID = userViews().id
var body: some View {
VStack{
Text("My Favorite")
.font(.title)
GeometryReader{mainView in
ScrollView(.vertical, showsIndicators: false) {
VStack{
ForEach(favorites.posts){post in
NavigationLink(destination: FavoriteDetail(post: post)) {
GeometryReader{item in
rentView1(post: post)
// scaling effect from bottom....
.scaleEffect(scaleValue(mainFrame: mainView.frame(in: .global).minY, minY: item.frame(in: .global).minY),anchor: .bottom)
// adding opacity effect...
.opacity(Double(scaleValue(mainFrame: mainView.frame(in: .global).minY, minY: item.frame(in: .global).minY)))
}
.frame(height: 100)
}
}
}
.padding(.horizontal)
.padding(.top,25)
}
.zIndex(1)
}
}
}
}
I'm afraid I'm doing something wrong or maybe I don't get how the ObservedObjects work with JSONDecoder.
Any help or explanation is welcome! Thank you.
解决方案
我在ForEach
里面使用时遇到了同样的问题ScrollView
检查这个讨论它可以帮助你找到一个黑客
推荐阅读
- sql - 防止存储过程 SQL Server 2008 中的参数嗅探?
- css - 如何在特色图像上获得背景色低不透明度叠加?
- java - 如何将`hamcrest-core-1.3.jar`添加到Windows中的类路径变量?
- java - Java 文本未正确更新
- jquery - 尝试使用 jQuery 或 CSS 删除 Squarespace 中的悬停覆盖
- angular - Angular ngModel 格式输出
- google-apps-script - 复制电子表格也会复制所有链接的文件
- php - 从 PHP Docker 运行 Python 脚本
- angular - Angular 6 防止 [hidden] 在页面加载时闪烁
- c - Malloc 错误:释放对象的校验和不正确 - 对象可能在释放后被修改