iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
0
Mobile Development

《菜鳥のSwift》持續30天開發挑戰系列 第 6

《DAY 6》使用表格元件

表格(Table View)可以將資料整齊的呈現在畫面上,今天來學習表格最基礎的用法。

首先在手機畫面中放入一個 Table View 元件,再用藍線設定 Table View 元件在 View Controller 上的 dataSource 與 delegate,並新增一個儲存格(Table View Cell)。
https://ithelp.ithome.com.tw/upload/images/20200920/20129680A4eaU4rW74.png

點選儲存格,設定它的識別碼。
https://ithelp.ithome.com.tw/upload/images/20200920/20129680hSpujTtfnh.png

開啟 ViewController.swift 讓類別符合 UITableViewDataSource 與 UITableViewDelegate 協定的規範。我們可以看到 Xcode 會報錯,因為我們還沒有寫三階段的對話函數。
https://ithelp.ithome.com.tw/upload/images/20200920/20129680D0oA8IiZJu.png

  • 寫在 extension 下,可以方便我們找到函數。

接著我們可以宣告一個陣列,裡面存放著我們要顯示的內容。

var list = ["音樂", "電影", "遊戲"]
  • 第一階段對話,表格上有多少區段?若不寫預設為一個區段。
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

如果區段有兩個以上並想做到間隔的效果,Table View 的 Style 請設成 Grouped。
https://ithelp.ithome.com.tw/upload/images/20200920/20129680S1uJFph1VJ.png

  • 第二階段對話,每個區段有多少筆資料?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return list.count // 因為我們要呈現 list 的內容,所以回傳 list 內的個數,當有兩個以上的區段時,要根據 section 做判斷
}
  • 第三階段對話,每筆資料的內容為何?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // Cell 就是我們的儲存格識別碼
    cell.textLabel?.text = list[indexPath.row]
    return cell
}

大功告成!
https://ithelp.ithome.com.tw/upload/images/20200920/201296805MQ4SoufnP.png


上一篇
《DAY 5》想在多個按鈕上重複使用已經設定好的外觀?
下一篇
《DAY 7》新增手機頁面
系列文
《菜鳥のSwift》持續30天開發挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言