UITableView
ios中的tableview有點像android中的listview或者recycleview,tableview由UITableViewCell組成,UITableViewCell負責(zé)顯示數(shù)據(jù)
(1)創(chuàng)建一個UITableViewCell
通過自定義view可以生成一個自定義cell,在相應(yīng)的類記得要繼承UITableViewCell

通過自定義view可以生成一個自定義cell
import UIKit
class paymentCellview: UITableViewCell {
@IBOutlet weak var label_date: UILabel!
@IBOutlet weak var label_status: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
(2)創(chuàng)建UITableView
在tableview中我們要繼承相應(yīng)的UITableViewDataSource和UITableViewDelegate
- UITableViewDataSource 表視圖數(shù)據(jù)源協(xié)議,用來控制表視圖的顯示內(nèi)容
- UITableViewDelegate 表視圖代理,用來控制cell高度和選中cell后的事件
import UIKit
class ViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: view.bounds, style: .grouped)
tableView.backgroundColor = UIColor.white;
view.addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
}
//MARK: UITableViewDataSource
// cell的個數(shù)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
// UITableViewCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellid = "testCellID"
var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
if cell==nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid)
}
cell?.textLabel?.text = "這個是標題~"
cell?.detailTextLabel?.text = "這里是內(nèi)容了油~"
cell?.imageView?.image = UIImage(named:"Expense_success")
return cell!
}
//MARK: UITableViewDelegate
// 設(shè)置cell高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
// 選中cell后執(zhí)行此方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath.row)
}
}
(3)關(guān)于tableview中的cell自適應(yīng)高度
去掉默認設(shè)置的cell的高度 在xib中設(shè)置好相應(yīng)的約束constraints即可
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 44.0
// }
(4)關(guān)于UITableViewDelegate\UITableViewDataSource執(zhí)行順序
執(zhí)行順序(iOS11 默認開啟可預(yù)估高度)
(開啟后先執(zhí)行cellForRowAtIndexPath后執(zhí)行heightForRowAtIndexPath)
- numberOfSections 調(diào)用代理確定有幾個分區(qū)
- 判斷是否有headerview和footervier 有就確定下每個分區(qū)表頭和表尾的高度
- heightForHeaderInSection \ heightForFooterInSection
- numberOfRowsInSection 確定每個分區(qū)cell的數(shù)量
- heightForRowAtIndexPath 確定每個cell的高度 根據(jù)每個selection和row的數(shù)量 循環(huán)執(zhí)行代碼
- cellForRowAtIndexPath 執(zhí)行以上順序后 調(diào)用返回Cell代理的方法獲取Cell
- heightForRowAtIndexPath 重復(fù)返回cell的高度
- willDisplay forRowAtIndexPath 將cell要顯示到屏幕上