【问题标题】:Calcul height of uiview after animating this one动画后计算uiview的高度
【发布时间】:2025-12-29 06:15:12
【问题描述】:

我有一个动画修改了 UIView 的约束,我需要知道这个 UIView 在动画之后但在动画开始之前的大小......

storyboard

当用户滚动 UITableView 时,我更新了黑色 UIView 的 heightConstraint,我需要更新 UIView 后的高度,因为我需要在函数 viewDidLayoutSubviews 中修复黄色 UIview 的高度。

这是我用来为 UIView 设置动画的代码:

self.headerIsCollapsed = true
self.heightProfilView.constant -= (self.view.bounds.height / 5)
UIView.animate(withDuration: 0.3, animations: {
   self.view.layoutIfNeeded()
   self.imageUserProfil.layer.opacity = 0
})

我需要这里的值:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    heightTopBar.constant = // here i need the height of the UIView after animating this
}

所以,问题是:如何在动画后预先计算 UIView 的高度?

【问题讨论】:

  • 自动布局会在纵断面高度降低后自动拉伸黄色视图,所以去掉黄色高度会自动拉伸
  • 动画后预先计算是什么意思?这没有意义。也许你之前的意思?
  • 是的,谢谢。我了解了约束,并且更好地理解了它是如何工作的。我的问题解决了

标签: ios iphone swift xcode


【解决方案1】:

只需使用UIView.animate()的完成块

UIView.animate(withDuration: 0.3, animations: {
    self.view.layoutIfNeeded()
    self.imageUserProfil.layer.opacity = 0
}) { (finished) in
    // get the view's height after animation here
}

除非您将持续时间指定为 0,否则完成块将在动画序列结束后执行。

【讨论】:

  • 谢谢,但我在代码动画之前需要这个值,因为我需要在 override func viewDidLayoutSubviews() 中初始化
【解决方案2】:

试试这个:

self.headerIsCollapsed = true
//create this property at instance level in your viewcontroller class
self.heightBeforeAnimation = self.heightProfileView.frame.size.height
self.heightProfilView.constant -= (self.view.bounds.height / 5)
UIView.animate(withDuration: 0.3, animations: {
  self.view.layoutIfNeeded()
  self.imageUserProfil.layer.opacity = 0
}){ (isCompleted) in
    //create this property at instance level in your viewcontroller class
   self.heightAfterAnimation = self.heightProfileView.frame.size.height
}

并调用任何函数并使用包含高度值的两个变量的值来设置视图的动画效果。

【讨论】:

  • 好的,谢谢!但是在这段代码运行之前可以知道self.heightAfterAnimation,因为我需要在 viewDidLoad 时修复元素的高度?
  • 将 self.heightBeforeAnimation = self.heightProfileView.frame.size.height 作为 viewDidLoad 中的第一条语句,我希望这是您想要的。但是对于您的信息,永远不要在 viewDidLoad 中做这种事情,因为在此调用期间,视图正在加载,因此所有视图都到达那里的尺寸,如果当时尝试获取任何与视图相关的属性,您可能会得到中间值。但是如果你想要这个,那么在 viewDidLoad 中执行 self.heightBeforeAnimation = self.heightProfileView.frame.size.height