首页 > 解决方案 > 动画下拉UIView时TableView单元格不改变高度

问题描述

点击时我有一个 UIView 动画下拉菜单。我想要实现的是,当我点击 tableView 单元格时 UIView 高度也会自动跟随高度变化。这是我的代码

class SubjectCell: BaseCell {
    lazy var tableView: UITableView = {
            let tv = UITableView()
            tv.delegate = self
            tv.dataSource = self
            tv.allowsSelection = false
            return tv
     }()

extension SubjectCell: UITableViewDelegate {
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

            return 80
     }

     func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
            return UITableView.automaticDimension
     }
}

// This is the view I want to animate
@IBOutlet weak var mainContainer: UIView!
    @IBOutlet weak var calendarView: JKCalendar!
    @IBOutlet weak var arrowImageView: UIImageView!

    @IBOutlet weak var mainContainerHeightConstraint: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        mainContainer.addGestureRecognizer(tapGesture)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @objc func handleTap(gesture: UITapGestureRecognizer) {
        if mainContainerHeightConstraint.constant == 75 {
            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.arrowImageView.image = #imageLiteral(resourceName: "up-chevron")
                self.mainContainerHeightConstraint.constant = 370
                self.calendarView.alpha = 1
            })
        } else {
            defaultConstraint()
        }
    }

    fileprivate func defaultConstraint() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.arrowImageView.image = #imageLiteral(resourceName: "down-chevron")
            self.mainContainerHeightConstraint.constant = 75
            self.calendarView.alpha = 0
        })
    }

这是我对 uiview 的配置。

动态单元格

我将 mainContainerView 设置为顶部、前导和尾随 = 0。高度 = 370。

在 mainContainerView 里面有一个包含另外 2 个视图的 stackView,并在 mainContainerView 中设置我的堆栈视图顶部、尾随、底部和前导 = 0

这是我模拟器中的结果 主体缺席

我仍然不知道如何设置 tableViewCell 所以它会自动改变。请帮我 :)

标签: swiftuitableviewtableviewuitableviewautomaticdimension

解决方案


您需要设置底部约束,mainContainerView以便根据您的约束计算行高并删除该heightForRowAt函数。另一个是每次你改变mainContainerView你需要打电话的高度

tableView.beginUpdates()
tableView.endUpdates()

让它重新计算你的行的新高度,它将适用。


推荐阅读