客製出自己的TableView
我選擇紀錄美食的資訊,cell顯示圖片、名字、資訊,點擊利用prepare傳資料給下一頁
1. 如果不使用Table View Controller,則需自己拉一個Table View到View Controller裡,再將Table View Cell放到Table View裡,如下圖
2. 點選我們的Table View,點不到可以從左邊列表點選,點完後將dataSource、delegate拉給View Controller
3. 接下來先將畫面拉一拉,將想要的圖片、文字放好,記得將Table View Cell設定identifier的名字
自由高度可以參考:
4. 接下來我們可以到ViewController.swift裡去設置我們要加的屬性了,繼承UITableViewDataSource,這時會出現錯誤,利用fix功能會自動跑出要自訂的函數
//設定要給予cell的屬性
var food : [Food] = [Food(image: "咖哩飯",name: "阿娟咖哩飯",opening_hr: "時間:\n11:00–21:00", address: "地址:台南市中西區保安路36號", information: "地址:台南市中西區保安路36號\n\n電話:06-2248134;06-2209246\n\n營業時間:11:00 - 21:00\n\n公休:週四\n\n推薦菜色:咖哩飯、雞肉飯、鴨肉羹\n\nFB:https://www.facebook.com/pages/阿娟咖哩飯鴨肉羹/329673023713547", theMenu: "阿娟菜單",storeMap: "阿娟地圖")]func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return food.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {//等等加}
5. 接下來要將cell上的物件拉outlet,這裡要注意不能直接拉到ViewController,要先創一個TableViewCell.swift檔案,將storyboard的Table View Cell的class導向剛創好的檔案裡,將要拉的outlet拉一拉
6. 我們可以開始去設定cell裡的內容了,利用到在第4步驟裡的tableView(_:cellForRowAt:)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "foodCell", for: indexPath) as? FoodTableViewCell else { return UITableViewCell() } cell.foodImage.image = UIImage(named: food[indexPath.row].image) cell.foodNameLabel.text = food[indexPath.row].name cell.addressLabel.text = food[indexPath.row].address return cell}
這樣就創好基本客製化了,接下來可以替這個Table View加一些想要的功能
prepare傳資料給下一頁
1. 首先創好要傳下一頁的ViewController與其控制的class,將要顯示的圖片或文字拉好outlet,接下來就產生要接收的變數用來給予這些圖片與文字
2. 接下來就可以到prepare裡去傳值了
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let controller = segue.destination as? StoreTableViewController let indexPath = self.foodTableView.indexPathForSelectedRow controller?.storeName = food[indexPath!.row].name controller?.information = food[indexPath!.row].information controller?.theMenu = food[indexPath!.row].theMenu controller?.storeMap = food[indexPath!.row].storeMap}
3. 回到目標的class裡將我們接收到的變數傳給outlet吧
這樣就完成傳遞資料的部分了,這樣就完成簡單的TableView與prepare
GitHub: