NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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()
    }
}

   

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])
        }
    }
}

   

Much appreciated!

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.