显示 uitableview 后更改 UITableViewCell 高度

Change UITableViewCell's height after tableview is shown

我有一个 tableview,每个 tableviewcell 都有一个按钮。

我想在单击单元格按钮时更改当前单元格高度。

我该怎么做?谢谢!

您应该将所有 tableviewcell 的高度存储在 NSMutableArray 中。

当用户点击 tableviewcell 的按钮时,在 NSMutableArray 中更新 height

在那之后 reload 你的 UITableView

希望这对您有所帮助。

  1. 创建一个包含所选单元格索引的数组

    var selectedCellIndexs : NSMutableArray = []
    
  2. 在didSelectRowAtIndexPath indexPath: NSIndexPath)函数中添加:

    self.selectedCellIndexs.addObject(indexPath)
    tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    
  3. 现在在 tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) 中,你需要做的就是检查单元格是否是所选数组的一部分,以及它是否 return不同的值。

    if (self.selectedCellIndexs.containsObject(indexPath)) {
        return selectedHeight 
    }
    return notSelectedHeight
    
  4. 请记住,如果要取消选择单元格,则需要在单击该单元格时从 selectedCellIndexs 中删除索引路径。

注意:这是用户选择单元格以更改高度时的基本工作流程。需要做更多的工作才能从按钮操作中获取单元格。

全局声明一个 mutableArray。

var buttonPressedIndexPaths : NSMutableArray = [] 

cellForRowAtIndexPath()方法中

cell?.button.tag = indexPath.row
cell?.button.addTarget(self, action: "onButtonAction:", forControlEvents: UIControlEvents.TouchUpInside)

复制粘贴这些方法

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
       if(buttonPressedIndexPaths.containsObject(indexPath))
       {
        return 90;//button pressed cell height
    }
    else
       {
        return 44;//normal
    }
}

func onButtonAction(sender:UIButton)
{
    var indexPath : NSIndexPath = NSIndexPath(forRow: sender.tag, inSection: 0)//section may differ based on ur requirement
    if(buttonPressedIndexPaths.containsObject(indexPath))
    {
        buttonPressedIndexPaths.removeObject(indexPath)
    }
    else
    {
        buttonPressedIndexPaths.addObject(indexPath)
    }
    tableView.reloadData();
}