首页 > 解决方案 > TableView 单元格:约束更改冲突 tableView.endUpdates()

问题描述

我有一个用 Swift 编写的消息传递应用程序。


它确实有消息气泡:if the message is longer than 200 chars它正在缩短。

每当用户单击一条消息时,它就会被选中:

但这两者似乎互相冲突,并制作了一个奇怪的动画:(看结尾)

https://youtu.be/QLGtUg1AmFw

代码:

func selectWorldMessage(indexPath: IndexPath) {

    if let cell = tableView.cellForRow(at: indexPath) as? WorldMessageCell {

        cell.messageLabel.text = data[indexPath.row].originalMessage
        self.lastContentOffsetY = self.tableView.contentOffset.y
        self.tableView.beginUpdates()
        UIView.animate(withDuration: duration) {


            cell.timeLabelHeightConstraint.constant = 18                

            cell.layoutIfNeeded()


        }

        self.tableView.endUpdates()
        self.lastContentOffsetY = nil
        cell.layoutIfNeeded()

         WorldMessageIdsStore.shared.nearby.saveCellHeight(indexPath: indexPath, height: cell.frame.size.height, expanded : true, depending: indexPath.section == 1 ? true : false )





    }
}
@objc func deselectSelectedWorldMessage(){
    if (currentSelectedIndexPath == nil){
        return
    }
    let indexPath = currentSelectedIndexPath!

    tableView.deselectRow(at: indexPath, animated: false)

    if let cell = tableView.cellForRow(at: indexPath) as? WorldMessageCell {

        cell.messageLabel.text = data[indexPath.row].shortenedMessage

        self.lastContentOffsetY = self.tableView.contentOffset.y
        self.tableView.beginUpdates()
        UIView.animate(withDuration: duration) {
            cell.timeLabelHeightConstraint.constant = 0                

            cell.layoutIfNeeded()



        }

        self.tableView.endUpdates()
        self.lastContentOffsetY = nil
        cell.layoutIfNeeded()


    }



    currentSelectedIndexPath = nil
}

有没有办法同时为单元格高度变化和约束变化设置动画?

我不能在零件中放置self.tableView.beginUpdates()和,因为它会导致新出现的行闪烁。self.tableView.endUpdates()UIView.animate(){ ... }

. . .

更新 1

所以如果我把self.tableView.beginUpdates()andself.tableView.endUpdates()放在 里面UIView.animate(){ ... },那么动画效果很好。但正如我提到的,当出现新行时它会导致闪烁。

视频:

https://youtu.be/8Sex3DoESkQ

更新 2 !!

因此,如果我将UIview.animate' 持续时间设置为0.3一切正常。我真的不明白为什么。

标签: swifttableviewconstraints

解决方案


这个动画可以是粘性的。

我认为你的主要问题是泡沫收缩得比它应该的多。如果你在慢动画模式下运行你的动画(顺便说一下,模拟器有这个选项,对调试非常有用)你会注意到:

气泡收缩

为了解决这个问题,你可以让你的标签垂直内容压缩阻力 更高,并检查标签也有高优先级的顶部和底部约束,所以它不会被这样切割。

https://medium.com/@abhimuralidharan/ios-content-hugging-and-content-compression-resistance-priorities-476fb5828ef


推荐阅读