UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Button Help

Forums > 100 Days of SwiftUI

I'm working on Rock, Paper, Scissors project in early stages. I'm trying to create three buttons but get the error "Trailing closure passed to parameter of type 'PrimitiveButtonStyleConfiguration' that does not accept a closure".

Code is exactly like in Guess the Flag game which does not produce the error.

What am I missing?...

import SwiftUI

struct ContentView: View {
    @State private var moves = ["Rock", "Paper", "Scissors"]
    @State private var correctAnswer = Int.random(in: 1...3)
    @State private var winOrLose = 0
    @State private var points = 0
    @State private var playCount = 0

    func shuffleMoves() {
        moves.shuffle()
    }

    func moveTapped(_ move: Int) {
        if move == 0 {
            //some code
        } else if move == 1 {
            //some code
        } else {
            //some code
        }
    }

    var body: some View {
        HStack {
            ForEach(0..<3) { number in
                Button {       <-------get error here
                    moveTapped(number)
                }
            }
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

For a Button you need an action and label, however there a a few ways to do it (the print() are the action

The label staight after the Button for simple text

Button("Tap Button") {
    print("Tap Button pressed")
}

The label in second trailing closure that show a View

Button {
    print("Tap Button pressed")
} label: {
    Text("Tap Button")
}

So you can do

HStack {
    ForEach(0..<3) { number in
        Button(moves[number]) {
            print(moves[number])
        }
    }
}

or

HStack {
    ForEach(0..<3) { number in
        Button {
            print(moves[number])
        } label: {
            Text(moves[number])
        }
    }
}

2      

Much appreciated!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.