首页 > 解决方案 > 如何使用 NavigationDestinationLink 转到另一个视图?

问题描述

我想使用 NavigationDestinationLink 转到另一个 SwiftUI 视图,但它不起作用。

在这里你可以看到我想要发送到我想要的页面但它不起作用的按钮项的代码

var body: some View {

    Button(action: {
            if self.type == "origin"{
                NavigationDestinationLink(SelectDestination(), isDetail: true)
            } else if self.type == "destination"{

                NavigationDestinationLink(TravelCostPage())
            }
        print("Button Clicked")
    }) {
        HStack{
            Spacer()
            VStack {

                Text(title)
                    .bold()
                    .color(.black)

                    Text("توضیحات")
                        .font(.footnote)
                        .color(.gray)

                    }
                    Image("grayStarIcon")
                        .renderingMode(.original)
                        .frame(width: 30, height: 30)

                        }.padding()
                            .frame(width: UIScreen.main.bounds.width, height: 50)
                    }


}

标签: swiftui

解决方案


这样做的正确对象是NavigationLink. 有了NavigationLink你可以控制导航。重要的是要注意NavigationLink仅在NavigationView.

因此,当您需要将导航移动到另一个视图时,您必须只使用NavigationLink包含一个Text或其他一些非交互式视图。内部定义的视图NavigationLink将用作Button

NavigationLink(destination: DestinationView()) {
    Text("click me")
}

高级示例:

import SwiftUI

struct HomeButton<Content>: View where Content: View {

    init(destination: Content, icon: String, title: String, description: String, color: Color, width: Length = .zero) {
        self.destination = destination
        self.icon = icon
        self.title = title
        self.description = description
        self.color = color
        self.width = width
    }

    let destination: Content
    let icon: String
    let title: String
    let description: String
    let color: Color
    let width: Length

    var body: some View {

        NavigationLink(destination: destination) {
            Group {
                ZStack {
                    Circle()
                        .foregroundColor(color)
                        .frame(width: 60, height: 60)

                    Text(icon)
                        .font(.system(size: 55))
                        .offset(x: -25, y: 20)
                }.offset(x: 12.5, y: 0)

                VStack {
                    Text(title)
                        .fontWeight(.bold)
                        .accentColor(.black)
                    Text(description)
                        .accentColor(.black)
                }.padding(.top, 0)
            }
            .frame(width: width == .zero ? nil : width)
            .padding(.top, 30)
            .padding(.bottom, 30)
            .padding(.leading, 45)
            .padding(.trailing, 45)

        }
        .background(
            Color.white
                .cornerRadius(6)
                .shadow(color: Color.lightGray, radius: 20))

    }

}

推荐阅读