简体   繁体   English

SwiftUI NavigationButton:如何导航到不同的目的地

[英]SwiftUI NavigationButton: How to navigate to different destinations

List(list) { feature in
                NavigationButton(destination: destination)) {
                    ListCell(feature: feature)
                }
            }

I want to navigate to different Views when tapping on row by changing the destination view instead of single View for each row 我想通过更改目标视图而不是每一行的单个视图来导航到不同的视图

is there a way to do it? 有办法吗?

Yes, there is a way. 是的,有办法。

This is the main body with a fully dynamic "cell". 这是具有完全动态“单元”的主体。 The tableRow function renders the content of the cell, while the destination function computes the target of the NavigationButton . tableRow函数呈现单元格的内容,而destination函数则计算NavigationButton的目标。

   var body: some View {
        List {
           // Renders the table with all the active conversations
           ForEach(appData.currentUser.conversations) { conversation in
                NavigationButton(destination: self.destination(for: conversation) ) { 
                    self.tableRow(for: conversation)
                }
            }
        }
    }

The destination function is very simple, the only "trick" here is the usage of AnyView as a return type. destination函数非常简单,这里唯一的“窍门”是将AnyView用作返回类型。

private func destination (for conversation: Conversation) -> AnyView {
    if conversation.mode == .personal {
        return AnyView(ConversationDetail(conversation: conversation))

    } else if conversation.mode == .groupChat {
        return AnyView(ConversationDetailGroup(conversation: conversation))

    } else {
        return AnyView(ConversationDetailJoin(conversation: conversation))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM