2017-02-17 108 views
0

我正在做一個四連勝的遊戲。我的主板上的每一個地方都是一個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條語句放在同一行(並且你不應該那樣做)。 –

回答

0

我猜你是通過直接改變中心物業經歷自動佈局衝突。您可能會在日誌中發現一些有趣的警告。特別是由於某些原因,UIButton不喜歡在自動佈局存在時手動移動。

要麼在故事板文件上關閉自動佈局,要麼調整按鈕的佈局約束,而不是修改其中心屬性。有幾個教程可以查找如何爲佈局更改設置動畫效果。

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

使用UIView.animate(withDuration:,animations:,completion:)並在completion封閉做到以下幾點:

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

希望有所幫助。