我需要删除一个部分中的一行,但它会删除上一节中的行。请帮助查找我的代码的问题。另外,请指教删除行时如何删除节?一个部分有一行。
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()
}
}
最佳答案
要删除空白部分,请将您的代码修改为:
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]]
关于ios - 如何使用 Swift 删除一个部分中的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722885/