ios - 如何使用 Swift 删除一个部分中的一行?

标签 ios swift uitableview

我需要删除一个部分中的一行,但它会删除上一节中的行。请帮助查找我的代码的问题。另外,请指教删除行时如何删除节?一个部分有一行。

    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/

相关文章:

swift - 使用 slider 在 2 个图像之间转换

ios - 无法再与 iOS 14 中的 UICollectionViewCell 或 UITableViewCell 中的内容交互

iphone - 如何使用 UITextInputMode

ios - 如何为多个 View Controller 使用 SWRevealviewcontroller 库

ios - 在 Swift 中重新加载 UIBarButtonItem

ios - Swift 交替 UITableViewCell 渐变颜色

ios - UITableViewCell 中没有调整大小

ios - 实体的核心数据可选属性如何工作?

iphone - 如何重新加载 UIViewController

ios - UITableView 延迟加载的图像在手指关闭之前不会加载