iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 23
0
自我挑戰組

菜比八iOS程式開發30天自我挑戰系列 第 23

Swift 4.2 Day-23 將表格 App 加上 Header

https://ithelp.ithome.com.tw/upload/images/20181107/20110801iOYW6hWWfA.png

當我們資料很多時又雜亂時該怎麼辦呢?我們可以設定一個叫”header”的Title,來將資料加以分類。
最常見到的就是手機裡的通訊錄,裡面各筆的資訊被按照名稱的不同排列在不同的地方。

https://ithelp.ithome.com.tw/upload/images/20181107/20110801Rq1eJ7LYlQ.png

我們先將 ViewController.swift 及 storyboard 中的 View Controller 刪除,接著在 storyboard 新增一個 Table View Controller,並新增一個 Cocoa Touch Class,選擇UITableviewController,按下 Next 選擇你要的儲存位置,點擊Create 確定儲存。連結storyboard中的Table view Controller 及 TableViewController.swift ,將 Identifier 設定為 Cell ,is initial View Controller 打勾。

https://ithelp.ithome.com.tw/upload/images/20181107/2011080139F9aY6WRz.png

回到 TableViewController.swift ,新增4個Array:

https://ithelp.ithome.com.tw/upload/images/20181107/201108019EypChRWsm.png

我們要做的就是將這學生依照他們所上的小學、國中、高中、大學來做分類。接著修改下列資料:

https://ithelp.ithome.com.tw/upload/images/20181107/20110801cONqMrIzKS.png

第一個函數設定總共有幾個 section ,我們共有 4 個陣列,因此回傳 4。
第二個函數設定每個 section 有幾個 row 。
接下來我們新增函數 tableVeiw(_:cellForRowAt:):

https://ithelp.ithome.com.tw/upload/images/20181107/20110801R8wuSJlbfz.png

執行結果:

https://ithelp.ithome.com.tw/upload/images/20181107/20110801T1gxXTI0MU.png

要在每個 section 加上 header 的話,新增函數 tableView(_:titileForHeaderInSection:):

https://ithelp.ithome.com.tw/upload/images/20181107/20110801MhLQjLAZf8.png

將想要顯示的 Title 設定好,若不想顯示就是用 nil 設定,就不會出現 header。
執行結果:

https://ithelp.ithome.com.tw/upload/images/20181107/20110801qX4G7xvnkC.jpg

覺得 header 高度太小嗎?新增函數 tableView(_:heightForHeaderInSection:):

https://ithelp.ithome.com.tw/upload/images/20181107/201108014cakuALfJb.png

設定高度為 30 ,執行結果:https://ithelp.ithome.com.tw/upload/images/20181107/20110801Y3RcnZ5Qnl.png


上一篇
Swift 4.2 Day-22 建立表格App
下一篇
swift 4.2 Day-24 自定 Header
系列文
菜比八iOS程式開發30天自我挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言