lgh lgh - 4 months ago 9x
Swift Question

Anonymously Instantiate UIButton in Array

I am making a sudoku game with Swift and iOS. The game has a 9 x 9 grid of UIButtons that serve as the game board. I am looking for a way to anonymously declare those buttons in an array or some other collection so I can interact with them, check validity, etc.

Is there a way to do this without ctrl-dragging form the scene to my ViewController for each button, declaring each as a named instance of UIButton, then operating on them in that method? This is the only way that I can think of to interact with them in some structured basis, but it is ugly and unmaintainable.


You could try creating an outlet connection. Or you can set the tag of each the buttons to a number, and search for them.

for subview in self.view.subviews {
    if subview.tag == aNumber {
        buttons.append(subview as! UIButton)

Make sure to call this in viewDidLayoutSubviews