我需要删除部分中的行,但它会删除上部的行。请帮助查找我的代码问题。另外,请告知删除行时如何删除该部分?一节中有一行。
var sectionTitles = [String]()
var savedURLs = [[String]]()
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return savedURLs.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return savedURLs[section].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SavingCell")
cell?.textLabel!.text = savedURLs[indexPath.section][indexPath.row]
return cell!
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
savedURLs[indexPath.section].removeAtIndex(indexPath.row)
NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)
savingTableView.reloadData()
}
}
答案 0 :(得分:2)
要删除空部分,请将代码修改为:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
savedURLs[indexPath.section].removeAtIndex(indexPath.row)
// now check if a section is empty and, if so, delete it
if savedURLs[indexPath.section].count == 0 {
savedURLs.removeAtIndex(indexPath.section)
}
NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)
savingTableView.reloadData()
}
}
虽然为了实现这一点,您的savedURLs
应为[[String]]
答案 1 :(得分:1)
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
savedURLs.removeAtIndex(indexPath.section)
NSUserDefaults.standardUserDefaults().setObject(savedURLs, forKey: Key_SavedURLs)
savingTableView.reloadData()
}
}
试试这个。这应该有用..