【问题标题】:Get Tag value while tapped Button in SwiftUI在 SwiftUI 中点击按钮时获取标签值
【发布时间】:2020-09-03 06:54:19
【问题描述】:

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】:

    tag中不需要,可以直接这样做,比如

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

    【讨论】:

    • 大部分循环都没有计数。大多数将由对象数组初始化。如果循环是对象数组而不是整数范围,如何获取标签?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多