简体   繁体   中英

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 .

   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.

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))
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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