为什么我的标签没有隐藏?

Why isn't my label hiding?

我有一个带有 stackView 的 tableViewCell。我试图让它成为一个可折叠的单元格。我可以在 tableView:cellForRowAt:

期间成功设置第二个标签的隐藏状态

但是,如果我更改隐藏状态以响应点击单元格,屏幕上的可见性不会改变。

UIView.animate(withDuration: 0.25) { [unowned self] in
    self.disclaimers.isHidden = !cellItem.isExpanded
}

cellItem.isExpanded 属性 与标签 .isHidden 属性 一样被正确切换。只是屏幕上没有变化。

我知道这已经在主线程上了,因为 tableView:didSelectRowAt: 在主线程上被调用。但是为了掩饰自己,我尝试用 DispatchQueue.main.async { } 调用而不是 UIView.animate 来换行。没有变化。

有什么想法吗?

如果你愿意,完整的项目在这里:https://github.com/AaronBratcher/TableViewTester

问题在 DisclaimersCell.swift。第 33 行

夫妻问题...

cellForRowAt 外,您永远不应在任何地方调用 .dequeueReusableCell。您在 TableViewController.swift -> didSelectRowAt ... 中执行此操作,这会创建单元格的 new 实例,not table 中的现有实例。将您的 guard 行更改为:

    guard var cellItem = helper.cellForRowAtIndexPath(indexPath) as? TableViewExpandableCellItem
        , let cell = tableView.cellForRow(at: indexPath) as? TableViewExpandableCell
        , cellItem.shouldExpand
        else { return }

这样,tableView.cellForRow(at: indexPath) 将 return 现有的 单元格。

接下来,动画设置 .isHidden 不会给你你想要的动画。

DisclaimersCell.swift -> toggleExpansion()中,更改:

    UIView.animate(withDuration: 0.25) { [unowned self] in
        self.disclaimers.isHidden = !cellItem.isExpanded
    }

简单地说:

    self.disclaimers.isHidden = !cellItem.isExpanded

然后,在您的 TableViewController didSelectRowAt 函数中:

    cellItem.isExpanded = !cellItem.isExpanded
    cell.toggleExpansion(tableViewCellItem: cellItem)

    tableView.beginUpdates()
    tableView.endUpdates()

这将告诉单元格 hide/show 标签,并且将 .beginUpdates()endUpdates() 配对将触发重新计算 table 中的行高,并为重绘。