SetTitle为一个按钮,并在单击两次时再次返回第一个标题

时间:2016-02-29 19:25:04

标签: ios swift uibutton uilabel

我设法通过点击它来更改按钮本身的标题和标签的文本。 最重要的是,我希望第二次点击时,标签中相同按钮的标题和相同的文字更改为AGAIN。考虑到我已经构建的代码,我该如何添加?

@IBOutlet weak var changeDegreeDisplay: UILabel!
@IBOutlet weak var radPressed: UIButton!

@IBAction func radianPressed(sender: AnyObject) {
        radPressed.setTitle("Deg", forState: .Normal)
        changeDegreeDisplay.text = "radians"
}

2 个答案:

答案 0 :(得分:0)

您可能希望使用if语句来检查按钮的当前标题或其状态,具体取决于您的用例。

@IBAction func radianPressed(sender: UIButton) {
  if sender.currentTitle == "Deg" {
    sender.setTitle("Rad", forState: .Normal)
  } else {
    sender.setTitle("Deg", forState: .Normal)
  }
}

答案 1 :(得分:0)

抓住按钮的标题,然后检查它是否是" Deg"或" Rad",然后将其切换为正确的。

@IBOutlet weak var changeDegreeDisplay: UILabel!
@IBOutlet weak var radPressed: UIButton!

@IBAction func radianPressed(sender: AnyObject) {
    let title = radPressed.titleForState(.Normal)
    if title=="Deg" {
        radPressed.setTitle("Rad", .Normal)
        changeDegreeDisplay.text = "degrees"
    } else {
        radPressed.setTitle("Deg", .Normal)
        changeDegreeDisplay.text = "radians"
    }
}

我建议将标题存储为常量,以便let degTitle = "Deg"let radTitle = "Rad",然后在条件中使用这些常量进行比较。