首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Xcode UIbutton函数

Xcode UIbutton函数
EN

Stack Overflow用户
提问于 2017-12-21 04:04:11
回答 2查看 150关注 0票数 1

我目前正在尝试创建一个点击器/金钱游戏,需要一些帮助。所以基本上这个应用程序由一个按钮组成,每次你点击它就会给+1个硬币。我想将金额从+1改为+2,如果您购买“双硬币换10枚硬币”为例。

Click here to see how the app looks right now, it might be easier to understand.

下面是一些可能相关的代码。

代码语言:javascript
复制
    @IBAction func button(_ sender: UIButton) {
    score += 1
    label.text = "Coins: \(score)"
    errorLabel.text = ""
    func doublee(sender:UIButton) {
        score += 2
    }


   @IBAction func points(_ sender: UIButton) {

    if score >= 10 {
    score -= 10
    label.text = "Coins: \(score)"
    doublePoints.isEnabled = false
    xLabel.text = "2X"
    xLabel.textColor = UIColor.blue
    } else {
        errorLabel.text = "ERROR, NOT ENOUGH MONEY"
    }

请记住,我刚刚开始编程,非常感谢所有的反馈。谢谢!

EN

回答 2

Stack Overflow用户

发布于 2017-12-21 04:53:30

添加一个变量,用于跟踪您在点击按钮时获得的分数,当您购买分数乘数时,相应地增加该变量,如下所示:

代码语言:javascript
复制
var scoreIncrease = 1 // this is how much the score increases when you tap

// This is called when the "CLICK HERE" button is tapped
@IBAction func button(_ sender: UIButton) {
    score += scoreIncrease
    label.text = "Coins: \(score)"
    errorLabel.text = ""
}

// This is called when you buy the 2x
@IBAction func points(_ sender: UIButton) {

  if score >= 10 {
     score -= 10
     label.text = "Coins: \(score)"
     doublePoints.isEnabled = false
     xLabel.text = "2X"
     xLabel.textColor = UIColor.blue
     scoreIncrease *= 2 // increase by x2
  } else {
     errorLabel.text = "ERROR, NOT ENOUGH MONEY"
  }
}
票数 1
EN

Stack Overflow用户

发布于 2017-12-21 05:10:40

如果我正确地理解了你的问题,你需要一些状态变量来保存每次点击需要添加到总得分中的硬币的值。

你可以这样做:

代码语言:javascript
复制
  class GameViewController: UIViewController {
     // this is your state variables
     var coinsPerClick = 1
     var score = 0

     override func viewDidLoad() {
      super.viewDidLoad()
      label.text = "Coins: \(score)"
      errorLabel.text = .empty
     }

     @IBAction func getCoins(_ sender: UIButton) {
      score += coinsPerClick
      label.text = "Coins: \(score)"
      // you can clear error label here
      errorLabel.text = .empty
     }

     @IBAction func doubleCoinsPerClick(_ sender: UIButton) {
      guard canUpgrade() else { 
       errorLabel.text = "ERROR, NOT ENOUGH MONEY"
       return
      }

      doublePoints.isEnabled = false
      score -= 10
      coinsPerClick *= 2
      label.text = "Coins: \(score)"
     }

     private func canUpgrade() -> Bool {
      return score >= 10 && doublePoints.isEnabled
     }
    }

关于您的代码的一些备注:

  1. 使用描述性名称
  2. 使用缩进在视觉上分隔代码块

我希望它能有所帮助。请随时询问更多问题

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47913596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档