使用Prototype Cell自訂表格視圖

執行結果

RestaurantTableViewController.swift 的程式碼:

import UIKit

class RestaurantTableViewController: UITableViewController {

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”,”Waffle & Wolf”,”Five Leaves”,”Cafe Lore”,”Confessional”,”Barrafina”,”Donostia”,”Royal Oak”,”CASK Pub and Kitchen”]

var restaurantImages = [“cafedeadend”,”homei”,”teakha”,”cafeloisl”,”petiteoyster”,”forkeerestaurant”,”posatelier”,”bourkestreetbakery”,”haighschocolate”,”palominoespresso”,”upstate”,”traif”,”grahamavenuemeats”,”wafflewolf”,”fiveleaves”,”cafelore”,”confessional”,”barrafina”,”donostia”,”royaloak”,”caskpubkitchen”]

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cellIdentifier = “datacell”

let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! RestaurantTableViewCell

//as!向下轉型

//設定自定類別的CELL屬性

cell.nameLabel.text = restaurantNames[indexPath.row]

cell.thumbnailImageView.image = UIImage(named: restaurantImages[indexPath.row])

return cell

}

override func viewDidLoad() {

super.viewDidLoad()

}

override func numberOfSections(in tableView: UITableView) -> Int {

return 1

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return restaurantNames.count

}

}

---------------------------------------------------------------------------------------------------------

RestaurantTableViewCell.swift 的程式碼:

import UIKit

class RestaurantTableViewCell: UITableViewCell {

@IBOutlet var nameLabel: UILabel!

@IBOutlet var locationLabel: UILabel!

@IBOutlet var typeLabel: UILabel!

@IBOutlet var thumbnailImageView: UIImageView!{

didSet{

thumbnailImageView.layer.cornerRadius = thumbnailImageView.bounds.width / 2

thumbnailImageView.clipsToBounds = true

//設定圖片視圖為圓型(半徑為圖片視圖寬度的一半)

//裁減超過thumbnailImageView範圍的圖片

}

}

override func awakeFromNib() {

super.awakeFromNib()

// Initialization code

}

override func setSelected(_ selected: Bool, animated: Bool) {

super.setSelected(selected, animated: animated)

// Configure the view for the selected state

}

}

--

--