我在标准单一视图项目中有一个标准UIButton
。我想在点击按钮时获取按钮的文本。但是,在Xcode 7.0 GM中,编译器要求我使用??
,?!
或!!
,我会遇到奇怪的行为。当试图解开文本时,会出现更奇怪的行为:只有三次展开才能完成。
@IBAction func buttonTapped(sender: AnyObject) {
print( sender.titleLabel?!.text ) // Optional("Button")
print( sender.titleLabel??.text ) // Optional("Button")
print( sender.titleLabel!!.text ) // Optional("Button")
print( sender.titleLabel?!.text! ) // Optional("Button")
print( sender.titleLabel??.text! ) // Optional("Button")
print( sender.titleLabel!!.text! ) // Button
}
这里发生了什么?
我见过
但sender
不是这里的数组,我看不到与这些答案的关联。
答案 0 :(得分:2)
这是因为AnyObject
。第一个?
用于"它是响应titleLabel
方法的对象吗?",第二个?
用于"是标题标签为零?"
如果您只是从Interface Builder连接按钮,则可以使用
@IBAction func buttonTapped(sender: UIButton)
答案 1 :(得分:1)
如果您确定发件人始终为UIButton
,那么为什么输入参数为AnyObject
。以下声明将解决您的问题:
@IBAction func buttonTapped(sender: UIButton) {
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Optional("Button")
print( sender.titleLabel!.text! ) // Button
}