#8 使用IBOUTLET,IBACTION&亂數創作有趣App-骰子猜大小

寫一個小App驗收現在swift 的應用能力,在這次的App程式中用到的UI元件image view,textfield,label,button,segmented control。

程式邏輯是TextField輸入要比的數字,segmented control選擇比大小,按下Button 後,image view 會亂數換骰子圖,此時要使用Timer 控制每次換骰子圖的周期時間及要換骰子圖的運作時間,要用到兩個Timer,一個Timer控制換圖時間,另一個Timer控制換圖顯示要持續多久時間,Timer運作完成後顯示亂數產生的骰子數的圖片,依選擇條件,判斷比大小的結果,顯示在Label,先看一下畫面和運作動態,畫面還沒有優化,只是雛型驗證程式功能用。

程式啟動時的畫面

程式運行的畫面

Timer 的寫法

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

timer1 = Timer.scheduledTimer(timeInterval: 0.3 ,target:self , selector: #selector( timerAction) , userInfo: nil,repeats: true )

timeInterval 運行間格 0.1sec, target : view controller,selector 要運作的func,repeats 是否要重覆運行, Timer.scheduledTimer放在程式中的位置要規畫好,若放在IBAction 內,只要IBAction執行Timer就會啟動,要停止Timer要條件判斷用timer1.invalidate()去停止計時,這個方式與其他語言用法不同 ,例如某些語言寫法是用isEnable(Boolean) 去開跟關Tick Count,swift 的Timer 有自動啟動和手動啟動(用Timer.fire()),依各位功能選用。

收鍵盤的方式只有寫一種收法-點空白處,要用delegate 的寫法

1.在 class ViewController: UIViewController,UITextFieldDelegate ←- 加UITextFieldDelegate

2.指定delegate — -> 加入 self.NumInputText.delegate = self

3. 寫func ->

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

self.view.endEditing(true)

}

以上三步驟可實現點空白收鍵盤功能,還有其他收法-點return….。

其他的如 optional type 的 optional binding, switch 的 segmented control index ,image view 的圖片顯示和動態換圖等這些功能多做幾次就能體會,日後畫面再優化後,這個App應該可以上架吧? 。

--

--