点击swift后UIButton没有响应

问题描述:

我正在做一个四连胜的游戏。我的主板上的每一个地方都是一个UIButton,我正在尝试做一个func来检查用户是否可以将芯片插入按下的按钮,当我的func返回false为一个按钮时,按钮不再响应...在这里感谢 是我的代码:点击swift后UIButton没有响应

class ViewController: UIViewController { 
//player1 = red, player2 = blue 
var activePlayer = 1; 
var activeGame = true; 
var gameState:[Int] = [0,0,0,0,0,0,0, 
       0,0,0,0,0,0,0, 
       0,0,0,0,0,0,0, 
       0,0,0,0,0,0,0, 
       0,0,0,0,0,0,0, 
       0,0,0,0,0,0,0]; 
let winningOptions = [[0,1,2,3]]; //just one option for now 
@IBAction func btnClicked(_ gridBtns : UIButton){ 
    print(gridBtns.tag); 
    let activePosition = gridBtns.tag - 1; 
    if gameState[activePosition] == 0 && activeGame{ 
     gridBtns.center = CGPoint(x: gridBtns.center.x , y: gridBtns.center.y - 500); 
     gameState[activePosition] = activePlayer; 
     if okToPutChip(gridBtns){ 
      if activePlayer == 1{ 
       gridBtns.setImage(UIImage(named: "red_chip.png"), for: []); 
       UIView.animate(withDuration: 0.5, animations: { 
        gridBtns.center = CGPoint(x: gridBtns.center.x, y: gridBtns.center.y + 500) 
       }); 
       activePlayer = 2; 
      }else{ 
       gridBtns.setImage(UIImage(named: "blue_chip.png"), for: []); 
       UIView.animate(withDuration: 0.5, animations: { 
        gridBtns.center = CGPoint(x: gridBtns.center.x, y: gridBtns.center.y + 500) 
       }); 
       activePlayer = 1; 
      } 
     }else{ 
      print("button will not show this again beacuse its not responding"); 
     } 
     for option in winningOptions{ 
      if gameState[option[0]] != 0 && gameState[option[0]] == gameState[option[1]] && gameState[option[1]] == gameState[option[2]] && gameState[option[2]] == gameState[option[3]]{ 
       print("winner!!!!") 
       activeGame = false; 
      } 
     } 
    } 
} 
//my func to check if there is no chips blow this position 
func okToPutChip(_ gridBtns : UIButton)->Bool{ 
    let position = gridBtns.tag-1; 
    print("********position = \(position)") 
    if position < 35 && gameState[position+7] == 0{ 
     print("now return false") 
     return false; 
    }else if position < 35 && gameState[position+7] != 0{ 
     print("here???") 
     return true; 
    } 
    return true; 
} 
+0

栅格是7x6 – Nutels

+0

您的'print(gridBtns.tag)'行是否正在执行? –

+0

顺便说一下,在Swift中不需要分号,你不应该包含它们。你需要的唯一时间是如果你把2条语句放在同一行(并且你不应该那样做)。 –

我猜你是通过直接改变中心物业经历自动布局冲突。您可能会在日志中发现一些有趣的警告。特别是由于某些原因,UIButton不喜欢在自动布局存在时手动移动。

要么在故事板文件上关闭自动布局,要么调整按钮的布局约束,而不是修改其中心属性。有几个教程可以查找如何为布局更改设置动画效果。

或者你可以做的事情低俗:

使用UIView.animate(withDuration:,animations:,completion:)并在completion封闭做到以下几点:

let superview = gridBtns.superview 
gridBtns.removeFromSuperview() 
gridBtns.translatesAutoresizingMaskIntoConstraints = false 
superview.addSubview(gridBtns) 

希望有所帮助。