0

我在子视图中设置了 NavigationLink 的样式,以便将其样式再次用于其他目的地。

这是代码:

struct ContentView: View {  
    var body: some View {
        NavigationView {
            VStack {
                styledNavigationLink(background-color: .red, symbol: "flame.fill", textlabel: "Great Stuff", nextDestination: "secondView()")
                styledNavigationLink(background-color: .blue, symbol: "snow", textlabel: "Cold Stuff", nextDestination: "thirdView()")
            }
        }
    }
}


struct styledNavigationView: View {
    @State var background-color: Color
    @State var symbol: String
    @State var textlabel: String
    @State var nextDestination: String
    
    var body: some View {
        NavigationLink(destination: nextDestination, label: {
            VStack {
                Image(systemName: symbol).foregroundColor(.white)
                Text(textlabel)
                    .foregroundColor(.white)
            }
        })
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(background-color)
        .cornerRadius(10)
        .shadow(radius: 10)
    }
}

样式效果很好,但我不知道如何实现新的目的地。我不使用字符串作为类型。

4

1 回答 1

0

您需要将样式导航链接设置为按目的地通用。

这是可能的解决方案(有一些复制)。使用 Xcode 11.4 / iOS 13.4 测试。

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                styledNavigationLink(background_color: .red, symbol: "flame.fill", textlabel: "Great Stuff", nextDestination: secondView())
                styledNavigationLink(background_color: .blue, symbol: "snow", textlabel: "Cold Stuff", nextDestination: thirdView())
            }
        }
    }
}

struct secondView: View {
    var body: some View {
        Text("Second")
    }
}

struct thirdView: View {
    var body: some View {
        Text("Third")
    }
}

// By the way, states in below view is not needed as they currently done
struct styledNavigationLink<Destination: View>: View {
    var background_color: Color
    var symbol: String
    var textlabel: String
    var nextDestination: Destination

    var body: some View {
        NavigationLink(destination: nextDestination, label: {
            VStack {
                Image(systemName: symbol).foregroundColor(.white)
                Text(textlabel)
                    .foregroundColor(.white)
            }
        })
        .frame(width: 300, height: 75, alignment: .center)
        .padding(.all, 20)
        .background(background_color)
        .cornerRadius(10)
        .shadow(radius: 10)
    }
}
于 2020-07-29T13:17:26.143 回答