【问题标题】:Create and define an Array of NSButtons for OSX为 OSX 创建和定义一个 NSButton 数组
【发布时间】:2016-03-31 04:25:42
【问题描述】:

试图在 OSX 的 ViewController 中创建可变数量的 NSButton。尝试通过定义一个 NSButtons 数组来做到这一点。 运行时出现致命错误:数组索引超出范围 (lldb)。 部分胜任 Swift 并且有些阅读障碍,将不胜感激。试图查看过去的答案,但找不到任何有用的东西。

var arrayOfButton: [NSButton] = []
    for counter in 0...3 {
        var tempButton = NSButton(frame: NSRect(x: 160 * counter, y: 40 * counter , width: 150, height: 30))
        print("created tempButton")
        arrayOfButton[counter] = tempButton
        arrayOfButton[counter].title = "Button \(counter)"
        self.view.addSubview(arrayOfButton[counter])
         }

【问题讨论】:

    标签: arrays swift macos nsbutton


    【解决方案1】:

    尝试追加到数组中;

      arrayOfButton.append(tempButton)
    

    【讨论】:

      【解决方案2】:

      您的数组中有 0 个按钮,但您将 counter 的索引调用为空数组,导致索引错误。尝试通过

      添加临时按钮

      arrayOfButtons.apend(temp)

      【讨论】:

        【解决方案3】:

        在您的代码中,您创建一个按钮数组,然后将其定义为空。

        var arrayOfButton: [NSButton] = []
        

        然后你进入一个循环并尝试寻址数组的第一个元素:

        arrayOfButton[counter] = tempButton
        

        但是你的数组是空的。它没有第一个元素。它没有任何元素。您还没有将任何内容放入数组中。数组元素 0 超出了数组的范围,因为没有元素 0。

        要将临时按钮放入数组中,您需要将其附加到数组的末尾:

        // Use append to put the temp button into the array
        arrayOfButton.append(tempButton)
        

        【讨论】:

        • 感谢 user2277872、@dreamriver 和 John。那是我的愚蠢!
        • func buttonPressed (button: NSButton?) { button!.title = "pressed" } 当我按下按钮时,动作没有被执行。如果我进行手动功能调用,它确实如此。
        【解决方案4】:

        arrayOfButton[counter] = tempButton.

        这是一个空数组。试图分配给它的第零个元素没有任何意义。尝试.append 填写您的数组。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-21
          • 2017-12-07
          • 1970-01-01
          • 1970-01-01
          • 2017-10-08
          • 2021-12-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多