【问题标题】:Compare Integers比较整数
【发布时间】:2017-02-11 13:25:06
【问题描述】:

我的项目中有两个按钮,它们将 score += 1 添加到两个单独的标签中。我的意图是比较标签中的整数是否相等,并在另一个单独的标签中给出结果(在本例中为整数),这向我展示了场景。但是通过按下两个按钮之一没有任何反应。标签显示整数相等,但这是不可能的,因为标签中的整数不再相等。

override func viewDidLoad() {
    super.viewDidLoad()

    if scoreAdd == scoreAdd1 {
        time.text = "\(regulargame)"
    }else {
        overtime = regulargame + 30
       time.text = "\(overtime)"
    }

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func btn1(_ sender: AnyObject) {
    scoreAdd += 1
    score1.text = "\(scoreAdd)"
}

@IBAction func btn2(_ sender: AnyObject) {
    scoreAdd1 += 1
    score2.text = "\(scoreAdd1)"
}

}

【问题讨论】:

  • 你认为你在哪里比较这些整数?
  • 在 if 语句中
  • 朱莉:在viewDidLoad。您是否也在每次点击时重新加载视图?
  • 不,我不会在每次点击时重新加载视图。
  • Juli:那为什么每次点击都会调用viewDidLoad

标签: ios swift xcode integer


【解决方案1】:

viewDidLoad 只会在加载 ViewController 的 View 时调用。如果你想在每次按下按钮时检查整数,你必须明确地这样做:

override func viewDidLoad() {
  super.viewDidLoad()
  self.setTimeText()
  // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func btn1(_ sender: AnyObject) {
    scoreAdd += 1
    score1.text = "\(scoreAdd)"

    self.setTimeText()
}

@IBAction func btn2(_ sender: AnyObject) {
    scoreAdd1 += 1
    score2.text = "\(scoreAdd1)"

    self.setTimeText()
}

/// Is called whenever a score changes
func setTimeText() {
    if scoreAdd == scoreAdd1 {
        time.text = "\(regulargame)"
    } else {
        overtime = regulargame + 30
        time.text = "\(overtime)"
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-24
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多