Student-LTB Student-LTB - 8 days ago 5
Swift Question

Array of buttons action error

I have been trying to make an array of buttons for a game of checkers. I have managed to get the buttons to display on the screen, but when pressed they give me an NSException error.

I think I have been following the format to assign the "buttonPressed" command to every button, but the error keeps on appearing ("No method declared with Objective-C selector 'buttonPressed').

Note: This is all within the view controller. Not updated to Swift 3 yet.

Here is the code:

func placeButtons(){
for i in 0..<(Int)(boardWidth){
var column: [UIButton] = []
for j in 0..<(Int)(boardHeight){ //make sure only place on 8x8 board
let tileRect = CGRect(x: 40+(40*i), y: 60+(40*j), width: 40, height: 40)
let button = UIButton(frame: tileRect)
button.setTitle("\(i), \(j)", forState: UIControlState.Normal)
button.titleLabel?.text = ("\(i), \(j)")
button.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside) //error is here
view.addSubview(button)
column.append(button)
//how make a new label for each button?
}
field.append(column)
}
}

func buttonPressed(sender: UIButton!){
if sender.titleLabel?.text != nil{
saysTurn.text = "\(sender.titleLabel)"
} else{

}
}

Answer

If you're using Swift 2.2 or higher (which you totally should), then this should work for you.

func placeButtons(){
    for i in 0..<(Int)(boardWidth){
    var column: [UIButton] = []
        for j in 0..<(Int)(boardHeight){ //make sure only place on 8x8 board
            let tileRect = CGRect(x: 40+(40*i), y: 60+(40*j), width: 40, height: 40)
            let button = UIButton(frame: tileRect)
            button.setTitle("\(i), \(j)", forState: UIControlState.Normal)
            button.titleLabel?.text = ("\(i), \(j)")
            button.addTarget(self, action: #selector(self.buttonPressed(_:), forControlEvents: .touchUpInside) //error is solved
            view.addSubview(button)
            column.append(button)
            //how make a new label for each button?
        }
    field.append(column)
    }
}

func buttonPressed(sender: UIButton!){
    if sender.titleLabel?.text != nil{
        saysTurn.text = "\(sender.titleLabel.text)" //Also you don't need a debug description of your label, you need its text attribute
    } else{

    }
}
Comments