iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 7
0
Software Development

挑戰 30天內送審一支APP 系列 第 7

# UITableView ( D day + 6 )

UITableView ( D day + 6 )

前兩天已經試著用 storyboard 來做出一個 app,今天我們試著將一些資料已條列式的方式呈現出來。
相信用過智慧型手機一定都看過這樣的版型

沒錯!這就是所謂的 tableview,也就是我們今天要練習的重點

  1. 首先建立一個名為”exSimpleTableview” 的 single view application.
  2. 在元件庫找到”tableview
  3. 將 tableview以拖曳的方式拉到 storyboard並且設定4個邊界條件
  4. 在”show the attributes inspector” 修改tableview的版型並且定義識別碼為”Cell ”
    Style -> :basic:
    identifier -> :Cell:
  5. 我們預計要做一個列出餐廳名稱的table view,所以我們先找到”viewController.swift” ,用一個名為 “rastaurantNames” 的陣列包含所有餐廳的名字 。
 var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke street Bakery", "Haigh's Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waggle & Wolf", "Five Leaves", "Cage Lore ", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK pub and kittchen"]
  1. 有了名字後,就要想辦法將名字顯示出來。這裡我們要用到所謂的 protocol (協定) 至於什麼是協定呢? 之後的我們會拿出來解釋
    所以我們要告訴 viewcontroller會用到這兩個 protocol : “UITableViewDataSource” 、”UITableViewDelegate
  2. tableview中的”一格”我們稱為一個”cell”,所以我們要告訴tablevie幾件事情
    8.1 這個view要有幾個cell?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return restaurantNames.count

8.2 這個view的內容要從哪裡來? cell是不是可以重複利用?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
        cell.textLabel?.text = restaurantNames[indexPath.row]
        
        return cell
        
        }
  1. 連結datasource 與 delegate
    雖然我們在 viewcontrollor.swift設定好 cell的資料以及相關規定,但是 stroyboard並不知道這些設定,所以我們要將他們連接
    9.1 按著Ctrl 將 tableview拖曳到 “View controllor

    9.2 在彈出的 outlet中點選 “dataSource
    9.3 用同樣的方式,在outlet中點選 “delegete
  2. 檢查設定

    點選”tableview”的 “Show the Attributes inspector”,檢查剛剛設定是否有加入
  3. 按下 RUN 就可以看到結果囉!!

上一篇
AutoLayout (D day + 5)
下一篇
UITableViewController ( D Day + 7)
系列文
挑戰 30天內送審一支APP 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言