如何在Swift中将按钮文本转换为变量? 到目前为止,这是我能想出来的,但是没有用:
var answer = "example"
@IBAction func Button1(sender: AnyObject) {
var answer = Button1.text
}
任何帮助将不胜感激。谢谢!
答案 0 :(得分:4)
要获得UIButton的标题,您必须联系其子UILabel:
@IBAction func Button1(sender: AnyObject) {
let button = sender as UIButton // as! for Swift 1.2
var answer = button.titleLabel!.text
}
答案 1 :(得分:1)
在动作函数中sender
是被点击的按钮,因此访问sender
作为UIButton,然后访问按钮的文本
@IBAction func Button1(sender: AnyObject) {
let theButton = sender as! UIButton
self.answer = theButton.titleForState(.Normal)!
}