3

我正在构建一个需要动态谓词的 SwiftUI 列表。该方法在这里讨论:https ://www.hackingwithswift.com/books/ios-swiftui/dynamically-filtering-fetchrequest-with-swiftui

到目前为止,这是我的代码:

struct SomeView: View {

    var collection: Collection
    var messages: FetchRequest<Message>

    init(collection: Collection) {
        let predicate : NSPredicate = NSPredicate(format: "collection = %@", collection)
        self.collection = collection
        self.messages = FetchRequest<Message>(entity: Message.entity(), sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)], predicate: predicate)
    }

    var body: some View {
        List(messages.wrappedValue, id: \.uniqueIdentifier) { message in
            // construct the UI
        }
    }
}

到现在为止还挺好。

我不知道该怎么做:我需要根据结果中的其他messages一些消息来转换元素(为简单起见,我们假设基于先前的消息)。messages[0] 看起来应该是一种特殊的方式。消息[1] 的外观取决于消息[0]。消息[2] 依赖于消息[1] 等等。我无法预先计算,因为它可能会随时间而变化。它应该在这个特定的获取请求/结果的上下文中计算。

我可以将其表示为 Message 对象上的一些瞬态计算属性,然后视图代码可以使用该属性进行分支。我可以有一个函数,在其中给出特定消息和消息数组,该函数查找消息和其他消息并基于此设置给定消息的状态。但是,SwiftUI 限制了我可以在 View 代码中执行的操作,我无法以这种方式执行函数。

我可以在访问 WrappedValue 的地方运行 map 或 flatmap,但它们不允许我访问集合的其他元素来做出决定(我认为?)。

在这种情况下,我将如何进行这种转换?

4

1 回答 1

3

如果我正确理解了您的描述(并考虑到这FetchedResults是 a RandomAccessCollection),我将采用以下方法

var body: some View {
    List(messages.wrappedValue, id: \.uniqueIdentifier) { message in
        rowView(for: message, from: messages.wrappedValue)
    }
}

func rowView(for message: Message, from result: FetchedResults<Message>) -> some View {
   // having .starIndex, .endIndex, .position, etc. do any dependent calculations here
   // and return corresponding View
}
于 2019-12-31T12:18:20.707 回答