按钮数组操作错误

时间:2016-11-25 21:23:18

标签: arrays swift button uibutton

我一直试图为一个棋盘游戏制作一系列按钮。我设法让按钮显示在屏幕上,但是当按下它们时会给我一个NSException错误。

我想我一直在按照格式为每个按钮分配“buttonPressed”命令,但错误一直出现(“没有用Objective-C选择器声明的方法'buttonPressed')。

注意:这都在视图控制器中。尚未更新到Swift 3。

以下是代码:

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{

    }
}

1 个答案:

答案 0 :(得分:0)

如果您使用的是Swift 2.2或更高版本(您完全应该使用),那么这应该对您有用。

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{

    }
}