【问题标题】:Changing button color in swift causes "exc bad instruction" error快速更改按钮颜色会导致“exc bad instruction”错误
【发布时间】:2015-02-21 18:26:43
【问题描述】:

所以我试图允许用户通过单击一个调用方法来更改所有按钮颜色的按钮来更改我的应用程序的配色方案。我的按钮调用了这个方法:

    @IBAction func changeColor(sender: UIButton) {
        if sender.currentTitle == "Green" {
            buttonOne.backgroundColor = UIColor.greenColor()
            buttonTwo.backgroundColor = UIColor.greenColor()
            buttonThree.backgroundColor = UIColor.greenColor()
            buttonFour.backgroundColor = UIColor.greenColor()
            buttonFive.backgroundColor = UIColor.greenColor()
            buttonSix.backgroundColor = UIColor.greenColor()
            buttonSeven.backgroundColor = UIColor.greenColor()
            buttonEight.backgroundColor = UIColor.greenColor()
            buttonNine.backgroundColor = UIColor.greenColor()
            buttonClear.backgroundColor = UIColor.greenColor()
            buttonPlus.backgroundColor = UIColor.greenColor()
            buttonMin.backgroundColor = UIColor.greenColor()
            buttonEq.backgroundColor = UIColor.greenColor()
            buttonX.backgroundColor = UIColor.greenColor()
            buttonDiv.backgroundColor = UIColor.greenColor()
            buttonSet.backgroundColor = UIColor.greenColor()
        }

    }

但是当我运行应用程序并单击按钮更改颜色时,它给了我一个“exc bad instruction”错误并将其打印到控制台:“致命错误:在展开可选值 (lldb) 时意外发现 nil”

如何更改按钮的颜色而不导致此错误?如果我添加一个“!”到最后解开也不起作用的可选项。有什么建议吗?

【问题讨论】:

  • 您可能需要重新连接您的 ibaction

标签: ios xcode swift xcode6


【解决方案1】:

currentTitle 是一个可选的,所以你应该这样做:

    if let currentTitle = sender.currentTitle {
        if currentTitle == "Green" {
            // set button colors here
        }
    }

【讨论】:

  • 这不是导致错误的原因。正如我所说,当我尝试更改按钮的背景颜色时出现错误,而不是当我检查当前标题是什么时。导致问题的行是“buttonOne.backgroundColor = UIColor.greenColor()”
  • 您没有说是哪条线路导致了问题。更好地表达你的问题。
猜你喜欢
  • 2015-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多