如何在Swift中将按钮文本转换为变量?

时间:2015-04-25 00:02:23

标签: ios swift uibutton

如何在Swift中将按钮文本转换为变量? 到目前为止,这是我能想出来的,但是没有用:

var answer = "example"

@IBAction func Button1(sender: AnyObject) {

    var answer = Button1.text
}

任何帮助将不胜感激。谢谢!

2 个答案:

答案 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)!
}