【问题标题】:Add UIButtons to array on ViewDidLoad将 UIButtons 添加到 ViewDidLoad 上的数组
【发布时间】:2018-06-10 12:37:29
【问题描述】:

我正在研究一个示例项目。

我正在尝试计算 ViewControllers 视图具有的 UIButtons 的数量,然后将它们添加到数组中,以便我可以通过编程方式访问它们,即更改颜色/标题等。

import UIKit

class ViewController: UIViewController
{
    var cardButtons: [UIButton]!

    let cardForegroundColour = UIColor.white
    let cardBackgroundColour = UIColor.orange

    lazy var game = ConcentrationGame(numberOfPairsOfCards: (self.cardButtons.count + 1) / 2)

    override func viewDidLoad()
    {
        for case let button as UIButton in self.view.subviews
        {
            button.backgroundColor = cardForegroundColour
            self.cardButtons.append(button)
        }

        print ("number of buttons /(self.cardButtons.count)")
    }

所以,它构建得很好,但在附加行上崩溃了:

线程 1:致命错误:打开包装时意外发现 nil 可选值

现在,如果我设置断点,button 对象就是有效对象。

我可以很好地更改所有颜色,但我无法将它们添加到cardButtons 的数组中。

我知道我可以将 cardButtons 设置为 Collection Outlet,并手动将它们连接起来,但我希望能够更改 UI 并且代码只是适应,因此添加更多按钮或删除一些按钮不会更改代码或需要手动重新布线。

我意识到问题在于我对选项的理解,但我认为开头的 ! 和具体的对象 button 是正确的方法。

【问题讨论】:

  • cardButtons = view.subviews.compactMap { $0 as? UIButton }
  • var cardButtons: [UIButton]! 声明一个初始为 nil 的可选项。由于您从未为其分配数组,因此当您尝试访问它时它会崩溃(因为它是隐式解包的)。只需像 Johannes 在他的回答中显示的那样创建一个空数组,并且根本不要使用可选项。
  • 还可以考虑创建一个UIButton 子类,例如CardButton 已经设置了正确的背景。

标签: ios swift uibutton uikit optional


【解决方案1】:

问题是cardButtonsnil

将此行 var cardButtons: [UIButton]! 更改为 var cardButtons = [UIButton]()

【讨论】:

  • 非常感谢!
  • 没问题。不要忘记勾选我的答案;)
  • 只需要等待它允许我将其标记为答案。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多