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 :)!

1 Answer 1

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

That worked for me, but when using it, i had to do: ButtonView(buttonText: "Play") { PlayView() }
I don't have enough reputation. Once I get it take for sure that I'll do it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.