Is there any way to delete the last row of a particular section in a UITableView without deleting that entire section? I would like to be able to remove the last row from a section but keep that section's header visible, as it indicates that the sections exists but has no data.
I've found multiple prior answers on StackOverflow, but their solutions all seem to be that you have to delete the section if you want to delete the last row of a section, e.g., How to delete the last row of a section?
答案 0 :(得分:0)
嗯,你的问题与UITableViewDataSource协议的工作方式有关,如果部分中没有任何内容,则不应显示该部分。
但你能做些什么呢?
有一种简单的方法,在dataSource numberOfRowsInSection中你可以做一个if,那个条件将验证你的dataSource计数是否等于零并返回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
// .
// .
// .
}
“哦,但现在桌面中间有一个白色单元格”
好的,让我们打破一下:
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
}
}
答案 1 :(得分:0)
......事实证明我的错误在其他地方。在这种情况下,我不小心尝试删除索引路径(1,2147483647)。这个错误的结果是因为我假设我用于该部分数据的数组包含我想要删除的对象。由于没有,[array indexOfObject:object]
等于2147483647
。奇怪的是,产生的错误是Invalid number of sections
而不是Invalid number of rows in section
。