在SwiftUI列表中从Realm呈现数据的正确方法是什么 [英] What is the right way to present data from Realm in SwiftUI List
问题描述
我正在尝试从 Realm
中获取所有项目,并将它们显示在 SwiftUI列表
中,但是我一直遇到错误.
I’m trying to fetch all of the items from Realm
and display them in a SwiftUI List
but I keep getting an error.
在 UIKit/Realm
应用程序中,我将创建一个 Results
变量来存储 Realm
中的所有项目,然后,在 viewDidLoad
方法中获取项目并将其分配给变量.我正在尝试在 SwiftUI
中执行相同的操作,但是我不确定如何构建代码,我不断收到一条错误消息,指出我的 Realm
模型应符合 StringProtocol
,我很确定这与我对 SwiftUI
中的 Binding
缺乏了解有关.
In a UIKit/Realm
application, I would just create a Results
variable to store all of the items from Realm
then, I would fetch items in the viewDidLoad
method and assign them to the variable. I'm trying to do the same thing in SwiftUI
but I'm not sure how to structure my code, I keep getting an error saying that my Realm
model should conform to the StringProtocol
, I'm pretty sure this has to do with my lack of understanding Binding
in SwiftUI
.
同样,我要做的就是从 Realm
获取所有项目,并将它们显示在 SwiftUI列表
中.
Again, all I’m trying to do is fetch all of the items from Realm
and display them in a SwiftUI List
.
这就是我所拥有的.
class User:Object{
@objc dynamic var name:String = ""
@objc dynamic var age:Int = 0
@objc dynamic var createdAt = NSDate()
@objc dynamic var userID = UUID().uuidString
override static func primaryKey() -> String? {
return "userID"
}
}
SwiftUI代码:
struct ContentView: View {
@State private var allUsers : Results<User>!
var body: some View {
VStack{
List{
ForEach(allUsers, id:\.self) { user in
Text(user) // the error points here
}
}
}.onAppear(){
self.updateUserResults()
}
}
func updateUserResults(){
allUsers = realm.objects(User.self)
}
}
错误:
初始化器'init(_ :)'要求'用户'符合'StringProtocol'
Initializer 'init(_:)' requires that 'User' conform to 'StringProtocol'
我想念什么?
推荐答案
可能你是这个意思
ForEach(allUsers, id:\.self) { user in
Text(user.name)
}
这篇关于在SwiftUI列表中从Realm呈现数据的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!