我使用这样的原型(prototype)单元在界面生成器中设置我的 TableView 标题部分
这是这个 TableView 标题部分的最终结果
数据实际上是动态的,如果可用的部分只有一个(比如说财务),我希望 TableView 标题部分不存在,只显示人名。下面是我使用的简化代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var sectionMember : [Department]?
var abcd = 2
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let IT = Department(name: "IT", member: ["joko", "santi","pipin","candra"])
let finance = Department(name: "Finance & Accounting", member: ["ririn","andri","bagus","reyhan"])
let security = Department(name: "security", member: ["anto","budi","rudi"])
let purchasing = Department(name: "Purchasing", member: ["lulu","rina","santi"])
sectionMember = [IT,finance,security, purchasing]
//sectionMember = [IT]
}
}
extension ViewController : UITableViewDelegate {
}
extension ViewController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return (sectionMember?.count)!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionMember![section].member.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! TableViewCell
let departmentMember = sectionMember![indexPath.section].member[indexPath.row]
cell.memberOfDepartment = departmentMember
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if abcd == 1 {
return nil
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell
cell.department = sectionMember![section].name
return cell
}
}
}
为了简化代码,我使用变量 abcd
,如果 abcd = 1
我希望该节标题被隐藏/删除/不存在,但如果 abcd 不是 1然后显示标题部分。
在方法viewForHeaderInSection
中,如果abcd = 1
,我返回nil
,但结果仍然显示标题部分,但是颜色是灰色的,我不知道为什么它是灰色而不是 Storyboard中的粉红色。那么如何摆脱下面的灰色部分呢?
最佳答案
如果只有一个部分,这里你给header赋了nil,但是也给了height
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if sectionMember?.count ?? 0 == 1 {
return 0.0
}
else {
return your height
}
}
还有, 你的功能
func numberOfSections(in tableView: UITableView) -> Int {
return (sectionMember?.count)!
}
永远不要像这样使用 bang 运算符.. 用默认值打开它
func numberOfSections(in tableView: UITableView) -> Int {
return self.sectionMember?.count ?? 0
}
关于ios - 如何以编程方式使用原型(prototype)单元格删除 TableView 节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103293/