Home > other >  Xcode 14 Grid of buttons
Xcode 14 Grid of buttons

Time:10-13

I am trying to create a grid of 100 buttons (10x10)

The code below creates them however how can I give them an ID so that I can identify each one and even hide them when I click on one or change its colour etc.?

func createButtonGrid(colourArray: Array<String>) {
    
    let spacing = 35
    var xPos = 25
    var yPos = 150
    
    for i in 0...99 {
        print(String(i))
        createButton(xPos:xPos, yPos: yPos, colour: colourArray[i] , title: String(i))
        xPos = xPos   spacing
        
        if i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i == 59 || i == 69 || i == 79 || i == 89 {
            xPos = 25
            yPos = yPos   spacing

        }
    }
}

func createButton(xPos: Int, yPos:Int, colour: String, title: String) {
    let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
    gridButton.configuration = plainButtonConfig(colour: colour)
    view.addSubview(gridButton)
}

CodePudding user response:

The following function will create the buttons, display them in a 10x10 grid and give them all a tag:

func initializeButtons() {
    let spacing = 35
    var xPos = 25
    var yPos = 150

    for i in 0...99 {
                    
        let gridButton = UIButton(frame: CGRect(x: xPos, y: yPos, width: 30, height: 30))
        gridButton.backgroundColor = UIColor.systemPink
        gridButton.layer.cornerRadius = 5
        gridButton.tag = i
        gridButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        view.addSubview(gridButton)
        
        xPos = xPos   spacing
        if i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i == 59 || i == 69 || i == 79 || i == 89 {
            xPos = 25
            yPos = yPos   spacing
        }
        newButtons.append(gridButton)
    }
    
}

Then we can create a function that will have an action when you click the button.

@objc func buttonAction(sender: UIButton!) {
    
    print(sender.tag)
    
}

CodePudding user response:

Refactor your createButton() method to return the button as the function result. Save your buttons into an array. You’re already using a for loop. The button’s index in the array will be the value of i for each pass through the loop.

  • Related