1

我正在设计一个简单的数独应用程序,并且需要在单击 81 个按钮中的任何一个时触发一个动作。我在 ViewController 中创建了一组 UIButton:

class SudokuBoardController : UIViewController {
@IBOutlet var collectionOfButtons: Array<UIButton>?

  override func viewDidLoad() {

    collectionOfButtons.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

    ...
  } 
}

我可以从情节提要中将按钮添加到数组中,好的,就在我尝试 addTarget 时,我收到以下消息:

Value of type 'Array<UIButton>?' has no member addTarget

这个问题有没有不涉及我为每个按钮创建 81 个不同输出的解决方案?

谢谢你的帮助!

干杯

4

2 回答 2

5

你有一个Array,所以你想遍历UIButton数组中的 s 。而且因为您使用的是 Swift,所以您会希望以一种 Swifty 的方式进行操作,而不是使用简单的for循环。

collectionOfButtons?.enumerate().forEach({ index, button in
    button.tag = index
    button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
})

这也很好地处理了可选的事实,collectionOfButtons如果它是nil,则什么都不做,而不是崩溃。

于 2016-02-05T16:01:42.567 回答
2

您需要遍历按钮数组并将目标添加到每个按钮。试试下面的代码

var index = 0
for button in collectionOfButtons! {
    button.tag = index // setting tag, to identify button tapped in action method
    button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
    index++
}
于 2016-02-05T15:51:08.647 回答