why i have to use print((sender as AnyObject).currentTitle!!) to print title and print(sender.currentTitle) not work?

huangapple go评论77阅读模式
英文:

why i have to use print((sender as AnyObject).currentTitle!!) to print title and print(sender.currentTitle) not work?

问题

Sure, here's the translation:

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

而在下面这个例子中,它起作用:

print((sender as AnyObject).currentTitle!!)

英文:

Why when I try to print button title i used print(sender.currentTitel) and isn't working.

And this in below it is work:

print((sender as AnyObject).currentTitle!!)

答案1

得分: 1

我假设您处于像这样的IBAction函数中:

    @IBAction func buttonTapped(_ sender: Any) {
        // 在这里打印
    } 

这是因为在创建IBAction时您声明的Any引用。有两种解决方案。

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

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

或者测试发送方的符合性:

    @IBAction func buttonTapped(_ sender: Any) {
        if let button = sender as? UIButton {
            // 打印(button.titleLabel?.text)
        }
    } 
  • 如果您的IBAction仅由按钮触发,解决方案1更好。
  • 如果您的IBAction由多个发送方使用,解决方案2可能是一种方法。

干杯

英文:

I assume you are in a IBAction function like this:

    @IBAction func buttonTapped(_ sender: Any) {
        // print here
    } 

This is due to the Any reference you declare when you create the IBAction. Two solution.

You can modify your IBAction like this:

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

or test the sender conformance:

    @IBAction func buttonTapped(_ sender: Any) {
        if let button = sender as? UIButton {
            // print(button.titleLabel?.text)
        }
    } 
  • Solution 1 is better if your IBAction is only triggered by button(s)
  • Solution 2 may be an approach if your IBAction is used by multiple senders

Cheers

huangapple
  • 本文由 发表于 2020年1月6日 23:26:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定