ios - SwiftUI 无法添加 onChange 事件

标签 ios swift swiftui xcode12

我有一个 View ,可以在其中显示我的消息列表。每当添加新消息时,我都想滚动到底部。我正在尝试添加 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
    }
}
我在这里做错了什么?
`ForEach
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)
                        }
                    }
                }
            })
        }
    }
}

关于ios - SwiftUI 无法添加 onChange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62685933/

相关文章:

ios - 如何从 REST API search.list 结果中过滤掉 YouTube 的内容屏蔽视频

macos - macOS 下 SwiftUI 增加模糊半径时是否可以去除四个边缘周围的黑色效果?

swift - 无法在 SwiftUI 中使用自定义 View

swift - tableView不显示数据值

swift - 使用元组而不是字典作为返回类型有什么优势?

swift - 使用 Firebase 和 Google pod 时发生链接器错误

swift - 如何检测 SwiftUI 中的点击手势位置?

android - microsoft band 如何从自定义磁贴读取心率或某些传感器数据并与移动应用程序通信?

ios - 以编程方式将 UICollectionView 嵌套在 UIVIew 中

ios - 使用 swiftyjson 和 swift 解析嵌入的 json