[在SwiftUI中点击按钮时获取标签值

问题描述 投票:1回答:1

SwiftUI中,我创建了一个按钮循环。

点击按钮时我必须获取标签值。

我已经尝试了很多次。我无法点击哪个按钮

HStack(spacing: 1) {
         ForEach(0...2, id: \.self) { j in
                            Button(action: {
                                // need button Tag
                               print("Tapped Button Tag:")
                            }, label: {
                                    Text("")
                            })
                            .tag("\(j)")
                        }
                    }
ios swift xcode button swiftui
1个回答
2
投票

标记中不需要,可以直接执行,例如

HStack(spacing: 1) {
         ForEach(0...2, id: \.self) { j in
                Button(action: {
                    // j is available here from context
                   print("Tapped Button Tag: \(j)")  // << here !!
                }, label: {
                        Text("")
                })
            }
        }

© www.soinside.com 2019 - 2024. All rights reserved.