Ios 如何使用Swift删除节中的行?
我需要删除节中的一行,但它会删除上节中的行。请帮助查找我的代码问题。另外,请告知删除行时如何删除节?一节中有一行Ios 如何使用Swift删除节中的行?,ios,swift,uitableview,Ios,Swift,Uitableview,我需要删除节中的一行,但它会删除上节中的行。请帮助查找我的代码问题。另外,请告知删除行时如何删除节?一节中有一行 var sectionTitles = [String]() var savedURLs = [[String]]() func numberOfSectionsInTableView(tableView: UITableView) -> Int { return savedURLs.count } func tabl
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]]
但我看不出您的代码有问题。在我看来,它应该像预期的那样工作。你能附上一些截图来说明你所面临的问题吗?嗨,安德烈,谢谢你的快速回复。太棒了!我再次检查了我的应用程序,这是应用程序中其他代码的问题。所以这里的代码很好。你能告诉我在删除行时如何删除节吗?一节中只有一行。当然,我会在2-3分钟内写出答案:)好的,安德烈,我想出来了,谢谢。是这样的:savedURLs.removeAtIndex(indexPath.section)fahad,也谢谢你。安德烈先回答,所以我选择了他的答案。你的也行。都做完了,一切都好。现在继续前进。祝您今天过得愉快!当UITableView上有deleteSections函数时,是否有特定的原因使用重新加载数据?流畅的动画过渡更加专业。@GlennHowes很抱歉现在才看到你的评论。当然,deleteRow是一种更好的方法。我没有将其包含在原始回答中的原因是,它需要更多的代码,并且与原始问题(处理空部分)没有直接关系:)
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()
}
}