Victor
Victor

Reputation: 504

Add Button by id for SwiftUI inside ForEach using shorthand argument name $0

How to add Button inside the ForEach ? Works with Text but no luck with Button. Will like to make use of shorthand argument name $0

import SwiftUI

struct ContentView: View {

    let emojiMoves = ["🗿", "🧻", "✂️"]

    var body: some View {
        HStack {
            ForEach(emojiMoves, id: \.self) {
                Text($0)
            }
        }
    }
}

Something like this could work but I like the simplicity of $0

ForEach(0 ..< self.emojiMoves.count, id: \.self ) { number in
                    Button(action: {
                        self.emojiMoves[(number)]
                    })   
                }

Upvotes: 0

Views: 712

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

ForEach(self.emojiMoves, id: \.self ) {
   Button($0){

   }
}

Upvotes: 1

Related Questions