範例表格程式(進階版)

接續上個禮拜的文章:範例表格程式

首先點開 Asset.xcassets 加入一張圖(隨機都行)將圖片名稱改為 restaurant

回到程式碼,加入以下程式碼第 13 行

import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var restarantNames = ["Cafe Deaned", "Homei", "Teakha"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restarantNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "datacell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
cell.textLabel?.text = restarantNames[indexPath.row]
cell.imageView?.image = UIImage(named: "restaurant")
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

這樣就可以把餐廳圖片(假裝那個人頭是餐廳)秀出來

加入以下程式碼可以隱藏狀態欄(第 18-20 行)

import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var restarantNames = ["Cafe Deaned", "Homei", "Teakha"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restarantNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "datacell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
cell.textLabel?.text = restarantNames[indexPath.row]
cell.imageView?.image = UIImage(named: "restaurant")
return cell
}
override var prefersStatusBarHidden: Bool{
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

這樣就可以把狀態欄隱藏

接下來將三張 user 的圖片放進來,並且改名成 restaurant1~3.素材參考:堆疊視圖

將程式碼改成以下模樣(新增第 5 行,修改第 14 行)

import UIKit
class ViewController: UIViewController, UITableViewDataSource {
var restarantNames = ["Cafe Deaned", "Homei", "Teakha"]
var restaurantImages = ["restaurant1", "restaurant2", "restaurant3"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restarantNames.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "datacell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
cell.textLabel?.text = restarantNames[indexPath.row]
cell.imageView?.image = UIImage(named: restaurantImages[indexPath.row])
return cell
}
override var prefersStatusBarHidden: Bool{
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}

執行模擬器,三張不同的餐廳(人?)可以正常顯示

SHXJ
Latest posts by SHXJ (see all)

發佈留言