ios - 添加和删​​除某个 UITableViewCell 下面的 UITableViewCell

标签 ios swift uitableview swift2

我正在尝试创建一个 tableview,其中有一个 uitableviewcell(cell1) 的子类,其中包含一个按钮等。当在 cell1 中单击该按钮时,该按钮应该在其正下方添加和删除 uitableviewcell(cell2) 的不同子类。我附上了一个非常糟糕的说明,说明了我想要发生的事情。 enter image description here

我尝试做的是,当点击按钮时,我将 cell2 插入到 cell1 的 array[indexPath.row+1] 处的单元格对象数组中,然后在点击关闭单元格时从数组中删除该对象.在我插入或删除单元格后,我重新加载 tableView 以更新它以反射(reflect)数组,但是这是它搞砸的地方并且没有像我认为的那样表现。下面的代码可以提供更好的图片:

var tableCellObjects: [NSObject] = [] //grab the cell objects from an API call and append the cell2Object when a cell1 is expanded


func moreButtonTapped(sender: UIButton) {

    var indexPath: NSIndexPath!

    if let superview = sender.superview {
        if let cell = superview.superview as? Cell1 {
            indexPath = tableView.indexPathForCell(cell)
        }
    }

    if tableCellObjects[sender.tag].isKindOfClass(Cell1Object) {
        let cell1Object = tableCellObjects[sender.tag] as! Cell1Object

        if cell1Object.expanded {
            cell1Object.expanded = false
            sender.setImage(UIImage(named: "MoreButtonClosed.png"), forState: .Normal)
            tableCellObjects.removeAtIndex(indexPath.row+1)

            tableView.reloadData()
        } else {
            cell1Object.expanded = true
            sender.setImage(UIImage(named: "MoreButtonOpen.png"), forState: .Normal)
            tableCellObjects.insert(Cell2Object(param1, param2: param2), atIndex: indexPath.row+1)
            tableView.reloadData()
        }

    }
}

最佳答案

当您的数据发生变化时,您应该更新数据源,然后插入/删除/重新加载索引路径。使用以下功能:

public func insertRowsAtIndexPaths(indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation)
public func deleteRowsAtIndexPaths(indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation)
public func reloadRowsAtIndexPaths(indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation)

我建议您使用.Fade 使动画流畅。

关于ios - 添加和删​​除某个 UITableViewCell 下面的 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802293/

相关文章:

arrays - addObjectsFromArray 错误 : how to convert `Array<Character>` to `[AnyObject]` ?

ios - SWIFT:在 performSegueWithIdentifier 之后未加载原型(prototype)单元格

ios - 设置表格 View 单元格的最小高度?

ios - 如何发布使用 xcodebuild build 命令生成的 ipa

iphone - UiBarButtonItem 背景图片直到第一次点击才显示

ios - 动画时将 UITableViewCell 子 UIImageView 置于前面

iphone - 在表格 View 中使用附件复选标记

ios - 如何从 swift 3 中的核心数据属性(列)中删除特定数据

swift - Playground 上没有 map 功能的输出

ios - 如何使用导航 Controller 快速重用 View Controller 对象