【问题标题】:How to change constraint of view in iOS swift 4?如何更改 iOS swift 4 中的视图约束?
【发布时间】:2018-01-24 10:30:23
【问题描述】:

我已经为视图高度的更改约束编写了此代码,但它不起作用。这会在没有动画的情况下更改我的视图高度并立即更改。

//MARK:Scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {

    if scrollView.contentOffset.y > 0 {
        self.topView.layoutIfNeeded()
        UIView.animate(withDuration: 3.0, animations: {
            self.topViewHeight.constant = 64
            self.topView.layoutIfNeeded()
        })
    }

}

【问题讨论】:

  • 动画前的常数是大于还是小于64?
  • @MilanNosáľ 之前大于

标签: ios uiview constraints constants swift4


【解决方案1】:

你需要在UIView.animate之外设置新的约束常量,同时调用setNeedsLayout()。此外,我猜您只想在开始时调用该动画一次,因此您可以实现一个简单的守卫来测试它是否已经展开(或折叠,取决于您要做什么)。

var isTopViewCollapsed = false

//MARK:Scrollview delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y > 0 && !isTopViewCollapsed {
        isTopViewCollapsed = true
        self.topView.superview?.layoutIfNeeded()
        self.topViewHeight.constant = 64
        // you need to tell the autolayout that constraints been changed 
        self.topView.superview?.setNeedsLayout()
        UIView.animate(withDuration: 3.0, animations: {
            self.topView.superview?.layoutIfNeeded()
        })
    }
}

【讨论】:

  • 立即更改常量
  • @reza_khalafi 立即尝试
猜你喜欢
  • 2023-03-13
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 2014-06-21
  • 2018-08-20
  • 1970-01-01
相关资源
最近更新 更多