多層選擇App -切換貓貓

Cindy
彼得潘的 Swift iOS / Flutter App 開發教室
5 min readMar 27, 2024

這次的作業希望能夠在畫面中使用到page control,segmented control,button & gesture (恩…好像在說廢話,跟標題一樣)

看起來是個複雜的作業!那就分成多個步驟,一步一步來!

以下是我的開發步驟

  1. 訂一杯飲料
  2. 設定計時器(記錄自己寫了多久,最終耗時3小時
  3. 主題發想
  4. 在Storyboard中拉出Outlet
  5. 思考資料結構
  6. segment & page 切換
  7. 利用好朋友GPT來下註解,並且優化程式碼

我想挑戰多層選擇,所以在segmented control的部分為切換貓咪花色,切換花色後利用page control來顯示該花色中所有的貓咪(圖片&姓名)

在button跟左右滑的gesture則是控制顯示不同的貓咪

拉出Outlet,以及畫面關聯

資料結構

因為是雙層選擇,所以利用兩個參數來記錄segment 跟page的當下index

從catData中整理出貓咪花色,並且render出segment的選項

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
renderCatColorSegment() // 從catData中整理出貓咪花色,並且render出segment的選項
}

func renderCatColorSegment() {
catColorAry = Array(catData.keys) // 從catData中取得所有貓的顏色
catColorSegment.removeAllSegments() // 先移除分段控制器中的所有選項,沒寫這句會有預設的

//用迴圈一個個將花色insert到segment中
for catColor in catColorAry {
catColorSegment.insertSegment(withTitle: catColor, at: catColorSegment.numberOfSegments, animated: false)
}
catColorSegment.selectedSegmentIndex = 0 // 預設選第一個segment(花色)

//預設顯示第一個segment的第一隻貓咪
updateCatInfo()
}

因為後來一直重複寫到貓咪的切換,這邊寫了一個func來呼叫

func updateCatInfo() {
if let getTargetCatAry = catData[catColorAry[currentColorIndex]] { //取得該花色的貓咪名字array
catImage.image = UIImage(named: getTargetCatAry[currentCatIndex])
catName.text = getTargetCatAry[currentCatIndex]
catPageControl.currentPage = currentCatIndex
}
}

按鈕切換前後一隻貓(左滑右滑的動作也關聯到這兒)

//前一隻貓
@IBAction func prePage(_ sender: Any) {
if let getTargetCatAry = catData[catColorAry[currentColorIndex]] { // 取得該花色的貓咪名字array
currentCatIndex = (currentCatIndex + getTargetCatAry.count - 1) % getTargetCatAry.count // 前一個貓index
updateCatInfo() // 用新的index來update新的貓咪畫面
}
}

//後一隻貓
@IBAction func nextPage(_ sender: Any) {
if let getTargetCatAry = catData[catColorAry[currentColorIndex]] { // 取得該花色的貓咪名字array
currentCatIndex = (currentCatIndex + 1) % getTargetCatAry.count // 後一個貓index
updateCatInfo() // 用新的index來update新的貓咪畫面
}
}

在切換花色時希望可以預設顯示該花色的第一隻貓

// 切換貓咪花色
@IBAction func colorSegmentChange(_ sender: Any) {
currentColorIndex = catColorSegment.selectedSegmentIndex // 更新選擇的貓顏色索引
currentCatIndex = 0 //切換segment時,貓咪的圖片index歸零
updateCatInfo() // 用新的index來update新的貓咪畫面
}

Demo

Github網址:https://github.com/cindy0344112/hellocat

--

--