App 的解鎖畫面(passcode)&& 亂數 計時器功能 Timer 簡單資料儲存 userdefaults()

成果展示

使用元件

#if else #Array # Timer #UserDefaults #switch

解鎖畫面

可參考這篇

使用switch 判斷使用者填入第幾項資料

func PasswordImage(){switch TypeWord.count {case 1:FristPasswordView.isHighlighted=trueSecondPasswordView.isHighlighted=falseThirdPasswordView.isHighlighted=falseFourthPasswordView.isHighlighted=falsecase 2:FristPasswordView.isHighlighted=trueSecondPasswordView.isHighlighted=trueThirdPasswordView.isHighlighted=falseFourthPasswordView.isHighlighted=falsecase 3:FristPasswordView.isHighlighted=trueSecondPasswordView.isHighlighted=trueThirdPasswordView.isHighlighted=trueFourthPasswordView.isHighlighted=falsecase 4:FristPasswordView.isHighlighted=trueSecondPasswordView.isHighlighted=trueThirdPasswordView.isHighlighted=trueFourthPasswordView.isHighlighted=trueCheckPassword()default:FristPasswordView.isHighlighted=falseSecondPasswordView.isHighlighted=falseThirdPasswordView.isHighlighted=falseFourthPasswordView.isHighlighted=false}
}

關於switch

使用方法:

switch 條件 {case 判斷條件1 : code for 1
case 判斷條件2 : code for 2 default: print( "default message")
  • 條件使用case ,在:寫上要執行的程式
  • 只要匹配case 就執行完畢 ,後面不必再接續處理
  • 必須包含所有case,或是使用default捕捉剩下的情況

輸入錯誤時清除Passwordview

func ClearPassword(){FristPasswordView.isHighlighted=falseSecondPasswordView.isHighlighted=falseThirdPasswordView.isHighlighted=falseFourthPasswordView.isHighlighted=falseTypeWord = ""}

骰子比大小

將骰子圖片存入Array

var Diceimage=["perspective-dice-one","perspective-dice-two","perspective-dice-three","perspective-dice-four","perspective-dice-five","perspective-dice-six"]

取亂數顯示圖片

YourDiceImage.image=UIImage(named: Diceimage[YourDice]) //我方骰子EnemyDiceImage.image=UIImage(named: Diceimage[EnemyDice]) //對手骰子

再透過if else 判斷勝負並加減分 搭配switch 顯示圖片

if YourDice>EnemyDice{Score+=1}if YourDice<EnemyDice{Score-=1}switch Score {case 1:ScoreImage.isHidden=falseScoreImage2.isHidden=trueScoreImage3.isHidden=truecase 2:ScoreImage.isHidden=falseScoreImage2.isHidden=falseScoreImage3.isHidden=truecase 3:ScoreImage.isHidden=falseScoreImage2.isHidden=falseScoreImage3.isHidden=falseGotoNextVC()default:ScoreImage.isHidden=trueScoreImage2.isHidden=trueScoreImage3.isHidden=true}if Score<1{Score=0}

計時器使用

透過Timer來設定固定時間執行function 設定固定 0.1 秒執行 runTimer

timer=Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(runTimer) , userInfo: nil, repeats: true)

func runTimer() 用counter 紀錄時間 並顯示在label上

@objc func runTimer(){counter+=0.1timeLabel.text = String(format: "%.1f", counter)
}

當答對時停止計時並透過使用UserDefault() 將資料存入 Key為 “GuessTime”

if self.timer != nil {self.timer.invalidate()stoptime=counterprint(stoptime)UserDefaults().setValue(stoptime, forKey: "GuessTime")//存資料}

希望這篇文章能夠幫助到你(妳)

如有錯誤指正

I hope you found this guide helpful. If not, then please let me know either in the comments below, I’m AlberLee

Swift#11

--

--