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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This answer worked too. Much obliged. :)
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++
}

1 Comment

Awesome, this worked, thanks Vishnu from a very grateful Swift newbie! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.