英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论