iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
0
Mobile Development

IOS 菜菜菜鳥30天挑戰系列 第 16

IOS 菜菜菜鳥30天挑戰 Day-16 tableview

tableView是我們接下來要說的東西,其實tableView我一開始是完全搞不懂在幹什麼(畢竟我是新手嘛),後來才發現是有跡可循的,那下面我來為大家實作與簡單講解吧!

tableview其實就是表格,表格要顯示內容的話需要一個自己的資料來源(datasource)和委任(delegate),這邊我會宣告一個陣列來當作我的資料來源

    var list = ["One","Two","Three"]

1.首先創立檔案後,在storyboard頁面,我們在右上角“+”號找到tableview並拖曳至view controller裡(約束要記得!)
https://ithelp.ithome.com.tw/upload/images/20200925/2012967939BJnTqqtU.png

2.打開viewcontroller.swift,我們要對tableview進行delegate和datasource指令,所以輸入以下程式

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
}

3.在我們輸入完之後你會出現下列報錯
https://ithelp.ithome.com.tw/upload/images/20200925/201296791C0miIKV7Q.png

按下fix即可,然後就會出現下列兩行程式,為了方便看我把它拉到viewDidLoad下面
https://ithelp.ithome.com.tw/upload/images/20200925/20129679lCrM4hO5wd.png
那來說明一下這兩行程式碼,numberOfRowsInSection就是一個區域有多少列,cellForRowAt則是我們要在cell(row)裡顯示的內容是什麼

4.接下來我們要做的事情是告知tableview要顯示幾行和顯示的內容,輸入以下的程式

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3 //顯示3行
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) //監聽我們現在所使用的cell
        cell.textLabel?.text = list[indexPath.row] //用list陣列的元素呈現內容
        return cell //回傳cell
    }

5.對了!上面步驟做完之後我才發現我們忘了讓tableview跟swift檔做連結(跑模擬機沒有呈現畫面)!記得拉outlet來做連結

    @IBOutlet weak var MyTableView: UITableView!

還有要讓他為自己delegate和datasource

    override func viewDidLoad() {
        super.viewDidLoad()
        MyTableView.delegate = self
        MyTableView.dataSource = self
        // Do any additional setup after loading the view.
    }

6.最後成果就是這樣了喔~
https://ithelp.ithome.com.tw/upload/images/20200925/20129679U06fbWfQSk.png


上一篇
IOS 菜菜菜鳥30天挑戰 Day-15 Alert是你嗎
下一篇
IOS 菜菜菜鳥30天挑戰 引入cocoapods!
系列文
IOS 菜菜菜鳥30天挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言