为什么我必须使用print((sender.currentTitle)来打印标题,而print(sender.currentTitle)不起作用?

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

为什么当我尝试打印按钮标题时使用print(sender.currentTitel)(不起作用)

并且它下面的工作:打印((发送为AnyObject).currentTitle !!)

ios swift iphone swift3 swift2
1个回答
0
投票
@IBAction func buttonTapped(_ sender: Any) { // print here }

这是由于您在创建IBAction时声明的Any参考。两种解决方法。

您可以像这样修改您的IBAction:

@IBAction func buttonTapped(_ sender: UIButton) { // print(sender.titleLabel?.text) }

或测试发件人的符合性:

    @IBAction func buttonTapped(_ sender: Any) {
        if let button = sender as? UIButton {
            // print(button.titleLabel?.text)
        }
    } 

如果您的IBAction仅由按钮触发,则解决方案1更好
    如果多个发件人使用您的IBAction,则解决方案2可能是一种方法
  • 欢呼声
  • © www.soinside.com 2019 - 2024. All rights reserved.