1.建立新專案後,於元件庫中將UITableViewController元件加入
2.將原本的ViewController刪除後,把Storyboard中的UITableViewController的Attribute中
"Is Initial View Controller"選項勾選起來
3.之後加入兩個新的Cocoa Touch class(左列檔案欄位中點滑鼠右鍵,選擇New File,新增cocoa touch class),分別為TableViewController(設定TableView中的
資料如何顯示)及TableViewCell(用來自定義Cell內含元件(Label,Image,Button...))
4.TableViewController內容如上圖所示,主要在
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
中回傳資料列數,在 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell中設定cell的reuse及元件對應到資料的方式(記得要在Attribute中設定Cell的identfier名稱,並且要把TableViewCell加在dequeueReusableCell後,這樣才能連結cell中宣告的元件)
範例:
TableViewController.swift
import UIKit
var Big = ["greg-rakozy-38802","greg-rakozy-53292","paul-earle-39322"]
var Detail = ["Sky View","Star View","Future View"]
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Big.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell1"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as!TableViewCell
cell.BigImage?.image = UIImage(named: Big[indexPath.row])
cell.detail?.text = Detail[indexPath.row]
return cell
}
TableViewCell.swift
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet var thumbImage: UIImageView!{
didSet{
thumbImage.layer.cornerRadius = 41.0
thumbImage.clipsToBounds = true
//將圖片轉成圓型
}
}
@IBOutlet var detail: UILabel!
@IBOutlet var BigImage: UIImageView!
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
}
}
-------------------------------------------------------
-------------------------------------------------------
留言
張貼留言