提问人:Zaher Mohamed Masloub 提问时间:1/6/2020 最后编辑:Ricardo GonzalezZaher Mohamed Masloub 更新时间:1/7/2020 访问量:160
为什么我必须使用 print((sender as AnyObject).currentTitle!!) 来打印标题和 print(sender.currentTitle) 不起作用?
why i have to use print((sender as AnyObject).currentTitle!!) to print title and print(sender.currentTitle) not work?
问:
为什么当我尝试打印我使用的按钮标题并且不起作用时。print(sender.currentTitel)
下面就是工作:
print((sender as AnyObject).currentTitle!!)
答:
1赞
jlngdt
1/6/2020
#1
我假设您处于这样的函数中:IBAction
@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 可能是一种方法
干杯
评论
!