Search code examples
iosuibuttonswift2xcode7addtarget

swift: Adding an action to an array of buttons


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


Solution

  • 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++
    }