嗯,您的问题与 UITableViewDataSource 协议的工作原理有关,如果该部分中没有任何内容,则不应显示该部分。
但是你能做些什么呢?
有一个简单的方法,在你的 dataSource numberOfRowsInSection 中你可以做一个 if,那个条件将验证你的 dataSource 计数是否等于 0 并返回 1,像这样:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRows = 0
switch section{
case 0:
numberOfRows = firstSectionArray.count()
case 1:
numberOfRows = secondSectionArray.count()
default:
()
}
if numberOfRows == 0 {
numberOfRows = 1
}
return numberOfRows
}
在cellForRowAtIndexPath中:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var numberOfRowsForThisSection = 0
switch indexPath.section{
case 0:
numberOfRowsForThisSection = firstSectionArray.count()
case 1:
numberOfRowsForThisSection = secondSectionArray.count()
default:
()
}
if numberOfRowsForThisSection == 0 {
return tableView.dequeueReusableCellWithIdentifier("blankCell") as! UITableViewCell
}
// Do the default implementation
// .
// .
// .
}
“哦,不过现在tableView中间多了一个白色的单元格”
好的,让我们打破它:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var numberOfRowsForThisSection = 0
switch indexPath.section{
case 0:
numberOfRowsForThisSection = firstSectionArray.count()
case 1:
numberOfRowsForThisSection = secondSectionArray.count()
default:
()
}
if numberOfRowsForThisSection == 0 {
return 0.0
}
}