【问题标题】:Adding and removing UITableViewCell below a certain UITableViewCell在某个 UITableViewCell 下面添加和删除 UITableViewCell
【发布时间】:2016-10-14 14:41:42
【问题描述】:

我试图有一个表视图,其中有一个 uitableviewcell(cell1) 的子类,其中包含一个按钮等。当在 cell1 中单击该按钮时,该按钮应该直接在其下方添加和删除不同的 uitableviewcell(cell2) 子类。我附上了一张很差的插图来说明我想要发生的事情。

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

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()
        }

    }
}

【问题讨论】:

  • 包含大量代码的简单问题。请只发布密钥代码。
  • 我删除了看起来像绒毛的代码。剩下的是我添加/删除单元格的功能。你说的关键代码就是这个意思吗?

标签: ios swift uitableview swift2


【解决方案1】:

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

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 来使动画流畅。

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2015-03-12
    • 2023-03-27
    相关资源
    最近更新 更多