【问题标题】:How to get a button sender id? in SwiftUI如何获取按钮发件人 ID?在 SwiftUI 中
【发布时间】:2021-09-03 11:35:18
【问题描述】:
                    Button(button1Name, action: messageMe)
                .frame(minWidth:0, maxWidth: 300)
                .padding()
                .foregroundColor(.white)
                .background(Color.gray)
                .cornerRadius(20)
                .tag("button1")
            
             }
         }
    }
}

func messageMe(//get sender) {
    print("Button Tag " //sender.id)
}

如何获取发送的按钮标签,以便根据按下的按钮运行操作?我知道这是非常基本的,但找不到 SwiftUI 的解决方案。大约 4 年后,我重新开始开发,而我心爱的 Objective-C 已经不复存在了!

【问题讨论】:

  • 将参数传递给你的函数(messageMe)可以解决这个问题
  • Objective-C 仍然存在 - 你可以在所有 iOS 框架中全面使用它,但如果你想使用 swift+SwiftUI,那么你需要学习新概念和 Swift 语言和 SwiftUI框架。
  • @Asperi 你会推荐我使用 Swift+SwiftUI 还是回到我的(首选)Objective-C?

标签: button swiftui ibaction


【解决方案1】:

你可以直接做,不需要tag这样的:

Button("Button title 1") {
  print("Button tapped!")
  messageMe(buttonId :"1")
}
.frame(minWidth:0, maxWidth: 300)
.padding()
.foregroundColor(.white)
.background(Color.gray)
.cornerRadius(20)

func messageMe(buttonId : String) {
  // use the buttonId
}

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 2019-02-16
  • 2015-05-10
  • 1970-01-01
  • 2020-10-02
相关资源
最近更新 更多