iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Mobile Development

IOS菜逼八連續30天挑戰系列 第 17

Day 17 UItableView的練習 (1/3)

上次做過調色盤的練習,對基本的東西有一些認識之後我們開始繼續往下練習~

其實TableViewy我們很常碰到,從手機裡的設定,到line聊天一行行的那種,都可以叫做tableview

我們來做一點有關Table View的練習

首先建立一個專案,建立好後去我們的Main.storyboard

把Table View 拉到我們的SuperView裏面,然後再把Table View Cell 拉進去,然後我們點選Table View Cell,右邊菜單有個Identifier,取名叫做cell

(這個Identifier是叫做儲存格識別碼,是用來做記憶體管理的)

然後到去ViewController.swift,在class ViewController裏,新增UITableViewDataSource,UITableViewDelegate,這兩個協定

設置@IBOulet跟dataSource

  @IBOutlet var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableview.dataSource = self
}

(別忘記到Main.storyboard建立連結)

新增好後,我們在底下新增兩個function,一個是
"numberOfRowsInSection"
這段意思是:總共有多少個Row在Section之中

我們假設他是 3個Row

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

第二個要新增的function是"cellForRowAt"
這段意思是:每個Row顯示的Cell為何

每筆資料顯示的Cell:(隨便你打,我這邊是打123)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = "123"
    return cell
}

最後補充一下Section,通常UItable View預設值就是一個Section,我們沒有特別去定義他,就只會出現一個Section,假設我們要新增3個Section,我們可以用下列程式碼完成:

func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

不過這樣不夠明顯,我們可以為每個Section增加標頭文字:

  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "section \(section)"
    }

好了之後應該會看到以下畫面:

基本到這邊,我們就對UITable View有一定基本的認識,下一篇我們來講一些其他的功能~


上一篇
Day 16 生命週期
下一篇
Day 18 UItableView的練習 (2/3)
系列文
IOS菜逼八連續30天挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言