动画约束,如何在所需方向上增加高度

时间:2019-02-19 09:06:26

标签: swift constraints snapkit

我使用SnapKit根据触摸事件更改UIView的高度。因此,当用户触摸单元格时,它会扩展。这样工作正常:

@objc func didRecieveTouch() {
    let originalHeight: CGFloat = 90
    let expandedHeight: CGFloat = 244

    if !expanded {
        self.snp.updateConstraints { make in
            make.height.equalTo(expandedHeight)
        }
    } else {
        self.snp.updateConstraints { make in
            make.height.equalTo(originalHeight)
        }

    }
    self.expanded = !self.expanded
    UIView.animate(withDuration: 0.25, animations: {
        self.superview?.layoutIfNeeded()
    })
}

问题在于,视图的生长方向对我来说很奇怪和错误。该视图实际上“跳”到新分配的空间,然后向上增长而不是向下增长,这是我想要的行为。

enter image description here

1 个答案:

答案 0 :(得分:-2)

将代码添加到动画块中。

UIView.animate(withDuration: 0.25) {
    if !expanded {
        self.snp.updateConstraints { make in
            make.height.equalTo(expandedHeight)
        }
    } else {
        self.snp.updateConstraints { make in
            make.height.equalTo(originalHeight)
       }
    }
    self.expanded = !self.expanded
    self.superview?.layoutIfNeeded()
 }