通过标记

时间:2017-08-15 13:24:28

标签: ios swift uibutton

我有一个游戏板(8x8阵列)。现在我想实现绘图功能,板中的每个单元都是一个带有单独标签的UIButton(从0到63)。如何通过按钮(带有单独标签的按钮)也可以使用setImage()函数?

我的一段代码:

for i in 0..<8 {
    for j in 0..<8{
        if gameBoard[i,j].rawValue == 1 {
            cellButton.setImage(UIImage(named:"whitePiece.png"), for: UIControlState())
        } else if (gameBoard[i,j].rawValue == 2){
            cellButton.setImage(UIImage(named:"blackPiece.png"), for: UIControlState())
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您发布的代码没有意义。看起来你有一个实例变量cellButton,并且你试图用它以某种方式在所有64个按钮上设置图像。那不可能奏效。如果按钮上有标签,可以使用以下内容:

假设您将标签号定义为100到188范围,其中10位是行号,1位是列号:

for i in 0..<8 {
    for j in 0..<8{
        //Create a tag number for this cell
        let tagNumber = 100 + i * 10 + j
        guard let aCellButton = view.viewWithTag(tagNumber) as? UIButton else {
          print("Error. Can't find button with tag \(tagNumber)")
          continue
        }
        if gameBoard[i,j].rawValue == 1 {
            aCellButton.setImage(UIImage(named:"whitePiece.png"), for: .normal)
        } else if (gameBoard[i,j].rawValue == 2){
            aCellButton.setImage(UIImage(named:"blackPiece.png"), for: .normal)
        }
    }
}

答案 1 :(得分:0)

您可以使用UIView viewWithTag方法通过标记访问子视图。

var tag = 0
for i in 0..<8 {
    for j in 0..<8{
         guard let buttonToSet = self.view.viewWithTag(tag) as? UIButton else{
               print("Couldn't find button")
               continue 
         }

        if gameBoard[i,j].rawValue == 1 {
            buttonToSet.setImage(UIImage(named:"whitePiece.png"), for: UIControlState())
        } else if (gameBoard[i,j].rawValue == 2){
            buttonToSet.setImage(UIImage(named:"blackPiece.png"), for: UIControlState())
        }

        tag = tag + 1
    }
}