2017-09-11 36 views
1

我有一個變量gameMode,我想在每次點擊屏幕時在垂直和水平之間切換。我遇到的問題是隻需要較低的變量,並且gameMode總是顯示爲水平。我該如何解決這個問題,以便在調用touchesBegan方法時進行切換?任何幫助表示讚賞!快速切換時在兩個變量之間來回切換的最佳方式

這裏是我有問題的代碼:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 


    if gameMode == "Horizontal" { 

     gameMode = "Vertical" 

    } 


    if gameMode == "Vertical" { 

     gameMode = "Horizontal" 

    } 


    print(gameMode) } 
+0

這可能是你要找的內容https://developer.apple.com/library/content/documentation/General/Conceptual/GameplayKit_Guide/StateMachine.html#//apple_ref/doc/uid/TP40015172-CH7- SW1 – 0x141E

回答

2

這是因爲,如果gameMode"Horizontal",你設置gameMode"Vertical"gameMode == "Vertical"回報true後,讓你設置gameMode"Horizontal"

試試這個代碼:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    if gameMode == "Horizontal" { 

     gameMode = "Vertical" 
    } else { 
     gameMode = "Horizontal" 
    } 

    print(gameMode) 
} 

您應該使用enum而不是字符串。

實施例:

enum GameMode { 
    case horizontal 
    case vertical 

    mutating func toggle() { 
     self = self == .horizontal ? .vertical : .horizontal 
    } 
} 

var gameMode: GameMode = .horizontal 

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    gameMode.toggle() 
    print(gameMode) 
} 
+0

爲方便起見,您也可以在該枚舉上做一個變異的func toggle()。 – Simon

1

可以與三元運算

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    gameMode = gameMode == "Horizontal" ? "Vertical" : "Horizontal" 
    print(gameMode) 
} 

切換兩種狀態只有兩種狀態可能是布爾變量比較適合。如果gameModeBool可以簡單的寫

gameMode = !gameMode 
+0

gameMode - 是Bool值的錯誤名稱。至於我,isHorizo​​ntal或isVertical會更好。但實現它的最好方法是使用枚舉GameMode。 –

+0

這個作品也謝謝你! – Justin

+1

由開發人員使用合理的名稱。這只是一個建議 – vadian

0

我將取代

if gameMode == "Horizontal" { 

    gameMode = "Vertical" 

} 


if gameMode == "Vertical" { 

    gameMode = "Horizontal" 

} 

if gameMode == "Horizontal" { 

    gameMode = "Vertical" 

} else { 

    gameMode = "Horizontal" 

} 

有兩個如果成一排,語句當您發送 「水平」 爲,該值會將其切換到「垂直」。這也將使第二個聲明起作用並將其切回。使用if/else將確保它只運行一次。