iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
0
Mobile Development

IOS App開發學習日誌系列 第 29

D29 1a2b小遊戲

  • 分享至 

  • twitterImage
  •  

昨天介紹了SwiftUI的@State與binding
今天我們用此宣告方法用在TextField元件來做出簡單的1a2b遊戲,主要畫面大致會如下圖
https://ithelp.ithome.com.tw/upload/images/20191015/20120980g2FE3APQD7.png

首先先宣告好需要使用到的@State變數
https://ithelp.ithome.com.tw/upload/images/20191015/20120980rVbS0bcVX2.png

  • test:用來存四個不同數字的陣列
  • showingAlert:判斷按下提交按鈕是否產生提示窗
  • ans:生成一個0到9的陣列並用shuffled()將其打亂,將打亂後的前四個數字當作答案
  • howmanyA、howmanyB:存幾A幾B的結果
  • result顯示判斷結果,預設為格式錯誤,若通過判斷式才將幾A幾B顯示出來

四個TextField用來輸入數值,並透過binding同步存到test陣列的指定位置
https://ithelp.ithome.com.tw/upload/images/20191015/20120980pt8hjTy5ku.png

為求方便我們先將ans[0]~ans[3]的數值當作答案顯示出來,以及重新產生答案的button
https://ithelp.ithome.com.tw/upload/images/20191015/20120980J0n0nEjbfp.png

最後將提交答案的button顯示出來,並在按下button後跳出提示窗顯示結果(若提交為0000則會顯示錯誤)
https://ithelp.ithome.com.tw/upload/images/20191015/20120980o145UBWEfD.png
https://ithelp.ithome.com.tw/upload/images/20191015/20120980b8leYVNoXh.png

有一點要提醒的是TextField預設為結束編輯後才將數值存到變數,若使用simulator的話記得要按下enter,
否則數值不會存進去


上一篇
D28 @State property、binding
下一篇
D30 NavigationView&NavigationLink
系列文
IOS App開發學習日誌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
deh
iT邦研究生 1 級 ‧ 2019-10-22 12:00:47

https://ithelp.ithome.com.tw/upload/images/20191022/20121952kg9VfAChXb.png

最後報錯了/images/emoticon/emoticon02.gif

我要留言

立即登入留言