ios - SwiftUI 无法添加 onChange 事件
问题描述
我有一个视图,其中显示了我的消息列表。每当添加新消息时,我都想滚动到底部。我正在尝试向其中添加一个onChange
事件,ForEach
但这会以一些奇怪的错误破坏我的代码:Referencing instance method 'onChange(of:perform:)' on 'Array' requires that 'Message' conform to 'Equatable'
有时The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
当我删除onChange
所有内容时都符合。
这是Message
模型:
struct Message: Identifiable {
var id = UUID()
var text: String
var createdAt: Date = Date()
var senderID: String
var seen: Bool
init(dictionary: [String: Any]) {
self.text = dictionary["text"] as? String ?? ""
self.senderID = dictionary["senderID"] as? String ?? ""
self.seen = dictionary["seen"] as? Bool ?? false
}
}
我在这里做错了什么?
`对于每个
struct MessagesView: View {
@ObservedObject var messagesViewModel: MessagesViewModel
var body: some View {
VStack {
ScrollView(.vertical, showsIndicators: false, content: {
ScrollViewReader { reader in
VStack(spacing: 20) {
ForEach(messagesViewModel.request.messages) { message in
Text(message.text)
.id(message.id)
}
.onChange(of: messagesViewModel.request.messages) { (value) in
reader.scrollTo(value.last?.id)
}
}
}
})
}
}
}
解决方案
如果您messages
是@Published
以下内容应该可以工作(正如我在Make a list scroll to bottom with SwiftUI 中测试的那样)
struct MessagesView: View {
@ObservedObject var messagesViewModel: MessagesViewModel
var body: some View {
VStack {
ScrollView(.vertical, showsIndicators: false, content: {
ScrollViewReader { reader in
VStack(spacing: 20) {
ForEach(messagesViewModel.request.messages) { message in
Text(message.text)
.id(message.id)
}
.onReceive(messagesViewModel.request.$messages) { (value) in
guard !value.isEmpty else { return }
reader.scrollTo(value.last!.id)
}
}
}
})
}
}
}
推荐阅读
- vhdl - 关于从行间距的文本中读取的问题
- sql - collect_list 保持顺序(sql/spark scala)
- sed - 如何使用sed通过行号将同一文件中的第N行替换为第M行
- javascript - 在 Postgres JSONB 中转义生成的单引号
- kubernetes - Canal CNI中cali*(veth)与flannel.1(vxlan)的关系
- r - 使用“which”提取非零 glmnet 系数时出错
- java - 有没有办法进行动态比较?我使用反射使其动态地排除字段,但它会减慢
- asp.net - 设置电子邮件系统不成功
- javascript - React 从包装器组件调用函数
- sql - 查询以组合列值