Search code examples
listviewnavigationviewswiftui-navigationlink

Multiple Destination Inside List SwiftUI


I have created a MenuList, a MenuListElementViewand a MenuListElement. In my MenuList

struct MenuList {
static let listData: [MenuListElement] = [
    MenuListElement(elementID: 0, icon: Constants.IconNames.smileyFace, title: Constants.IconTitles.title1, color: Constants.Colors.gray, numbers: 2),... 
 }

and so on I have created 10 separate list elements.

In my MenuListElement

struct MenuListElement: Identifiable {
var id: Int {
    return elementID
}
var elementID: Int
var icon: String
var title: String
var color: Color
var numbers: Int
}

In my MenuListElementView, I simply designed how each of the list elements must be. enter image description here

Finally, I designed this MenuView

enter image description here

Now, what I want to do is to go to a different destination in each MenuListElementwhen tapped in this code.

 NavigationView{
            List(MenuList.listData) { item in
                    MenuListElementView(item: item)
            }
        }

Let's say that I want to go to AuthorView when Yazarlar is tapped on the MenuLView and to SearchView when Arama is tapped. I want 10 different destinations View.


Solution

  • I have modified my MenuListElement to be able to send a view inside with it.

    struct MenuListElement: Identifiable {
    var id: Int {
        return elementID
    }
    var elementID: Int
    var icon: String
    var title: String
    var color: Color
    var numbers: Int
    var view: Any
    }
    

    I have changed my List view to

    List(MenuList.listData) { item in
                Button(action: {
                    self.isOpen = true
                }) {
                    MenuListElementView(item: item)
                        .fullScreenCover(isPresented: $isOpen) {
                            AnyView(_fromValue: item.view)
                        }
                }
            }
    

    and changed my MenuList to

    struct MenuList {
    static let listData: [MenuListElement] = [
        MenuListElement(elementID: 0, icon: Constants.IconNames.smileyFace, title: Constants.IconTitles.title1, color: Constants.Colors.gray, numbers: 2, view: MembershipView()),...
    

    In this way every list element has view information in them so with a button, I can directly pass to a view I want.