1

I'm designing a simple Sudoku app and need to trigger an action when any one of the 81 buttons are clicked. I created an array of UIButtons in my ViewController:

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

  override func viewDidLoad() {

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

    ...
  } 
}

I'm able to add the buttons to the Array from the storyboard ok, its just when I try to addTarget I get this message:

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

Is there a solution to this problem that does not involve me creating 81 different outputs for each button?

Thanks for your help!

Cheers

colinmcp
  • 446
  • 2
  • 5
  • 19

2 Answers2

5

You have an Array, so you want to iterate over the UIButtons in the array. And because you're in Swift, you'll want to do so in a Swifty way, not using a simple for loop.

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

This also nicely handles the fact that collectionOfButtons is an optional by doing nothing if it is nil, as opposed to crashing.

Gavin
  • 8,204
  • 3
  • 32
  • 42
2

You need to iterate through array of buttons and add target to each of the button. Try out following code

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++
}
Vishnu gondlekar
  • 3,896
  • 21
  • 35