首先應(yīng)該在你想要添加表格的控制器上創(chuàng)建表格
let tableV = UITableView.init(frame: self.view.frame, style: UITableViewStyle.grouped)
tableV.delegate = self
tableV.dataSource = self
self.view.addSubview(tableV)
別忘了遵守?cái)?shù)據(jù)源協(xié)議
其次就是重點(diǎn) 分組了
舉個(gè)例子
我們分三組猜旬,如果使用自定義表格的話 可以創(chuàng)建三繼承于UItableviewcell的控制器,選擇上xib這樣會簡單容易理解一些
下面就是代碼了
在外面填寫分組方法
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 || section == 2 {
return 1
}else{
return 3
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
return cell!
}else if indexPath.section == 1{
let cell = tableView.dequeueReusableCell(withIdentifier: "two")
return cell!
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: "three")
return cell!
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
//返回分區(qū)頭部視圖
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.white
let titleLabel = UILabel()
titleLabel.text = "午安·北京"
titleLabel.textColor = UIColor.black
titleLabel.sizeToFit()
headerView.addSubview(titleLabel)
return headerView
}
//返回分區(qū)頭部高度
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
在didload里面注冊cell
//注冊xib
tableV.register(UINib.init(nibName: "OneTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
tableV.register(UINib.init(nibName: "TwoTableViewCell", bundle: nil), forCellReuseIdentifier: "two")
tableV.register(UINib.init(nibName: "ThreeTableViewCell", bundle: nil), forCellReuseIdentifier: "three")
也是在里面我們填寫表格頭部視圖的字體
//設(shè)置分區(qū)頭尾的文字顏色:黑色
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self])
.textColor = UIColor.black
//設(shè)置分區(qū)頭尾的文字樣式:20號斜體
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self])
.font = UIFont.italicSystemFont(ofSize: 30)
然后在你的xib里面填寫你想要用到的控件就完成啦!!