2

I’m new at SwiftUI and I’ve a doubt. I wonder if anyone can help me.

I’ve a screen with two exact buttons (except for the text that they display and the view which they lead to). When they are tapped, each button leads the user to a new given view.

The code is this:


HStack {
    NavigationLink(destination: PlayView()) {
        ButtonTextView(buttonText: "Play")
    }
    .frame(width: 120, height: 40, alignment: .center)
    .background(Color(red: 242/255, green: 242/255, blue: 242/255, opacity: 1))
    .cornerRadius(10.0)
    Spacer()
    NavigationLink(destination: RankingView()) {
        ButtonTextView(buttonText: "Ranking")
    }
    .frame(width: 120, height: 40, alignment: .center)
    .background(Color(red: 242/255, green: 242/255, blue: 242/255, opacity: 1))
    .cornerRadius(10.0)
}

And I want to be able to do something like this:

HStack {
    ButtonView(buttonIdentifier: "Play")
    Spacer()
    ButtonView(buttonIdentifier: "Ranking")
}

Where ButtonView is defined like so:

NavigationLink(destination: PlayView()) {
    ButtonTextView(buttonText: "Play")
}
.frame(width: 120, height: 40, alignment: .center)
.background(Color(red: 242/255, green: 242/255, blue: 242/255, opacity: 1))
.cornerRadius(10.0)

So, basically, I don’t repeat code and have a much more readable file.

The problem comes when I’ve to define the destination of the NavigationLink. There is some way I can set the destination to be a variable and pass it when I call ButtonView()? So that if the buttonIdentifier is "Play", destination is PlayView() (like above) and if is "Ranking", then is RankingView().

I hope I’ve been able to explain my problem clearly (i’m not a native speaker…)

Any help is appreciated. Thanks a lot :)!

paalma
  • 81
  • 7

1 Answers1

2
struct ButtonView<Destination>: View where Destination : View {
    let buttonText: String
    let destination: Destination
    
    init(buttonText: String, @ViewBuilder destination: @escaping () -> Destination) {
        self.buttonText = buttonText
        self.destination = destination()
    }
    
    var body: some View {
        NavigationLink(destination: destination) {
            Text(buttonText)
        }
        .frame(width: 120, height: 40, alignment: .center)
        .background(Color(red: 242/255, green: 242/255, blue: 242/255, opacity: 1))
        .cornerRadius(10.0)
    }
}

Use like:

ButtonView(buttonText: "Play") {
    PlayView()
}
malhal
  • 26,330
  • 7
  • 115
  • 133