You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

取消UIViewPropertyAnimator动画后UIKit安全区域计算异常问题

关于UIViewPropertyAnimator取消动画后safeAreaLayoutGuide不同步的问题

场景描述

使用UIViewPropertyAnimator实现视图从初始帧CGRect(x: 10, y: 10, width: 100, height: 100)到目标帧CGRect(x: 10, y: 10, width: 300, height: 300)的动画,并添加了动画过程中暂停并反向取消的功能。首次取消动画时,视图帧与安全区域布局帧匹配;但第二次取消时,视图帧已重置为初始值,safeAreaLayoutGuide.layoutFrame的宽度却仍保持300,二者无法同步。

实现代码

启动动画的代码

@objc func onTap() {
    animator = UIViewPropertyAnimator(duration: 3, curve: .easeIn)
    
    animator.addAnimations {
      self.testView.frame = CGRect(x: 10, y: 10, width: 300, height: 300)
    }
    
    animator.addCompletion { pos in
      print("test view frame:::", self.testView.frame)
      print("test view safe frame:::", self.testView.safeAreaLayoutGuide.layoutFrame)
      print("test view safe inset:::", self.testView.safeAreaInsets)
      print("test view keyboard frame:::", self.testView.keyboardLayoutGuide.layoutFrame)
    }
    animator.startAnimation()
}

暂停并取消动画的代码

@objc func cancelTheAnimation() {
    animator.pauseAnimation()
    animator.isReversed = true
    
    let progress = animator.fractionComplete
    
    animator.continueAnimation(
      withTimingParameters: UICubicTimingParameters(animationCurve: .linear),
      durationFactor: 1 - progress)
}

控制台输出

------- animation completion ------
test view frame::: (10.0, 10.0, 100.0, 100.0)
test view safe frame::: (0.0, 37.0, 100.0, 63.0)
test view safe inset::: UIEdgeInsets(top: 37.0, left: 0.0, bottom: 0.0, right: 0.0)
test view keyboard frame::: (-10.0, 100.0, 390.0, 734.0)
------- animation completion ------
test view frame::: (10.0, 10.0, 100.0, 100.0)
test view safe frame::: (0.0, 37.0, 300.0, 263.0)
test view safe inset::: UIEdgeInsets(top: 37.0, left: 0.0, bottom: 0.0, right: 0.0)
test view keyboard frame::: (-10.0, 300.0, 390.0, 534.0)

疑问

这是UIKit的bug吗?如果不是,该如何修复才能让安全区域布局帧与视图帧同步?


内容的提问来源于stack exchange,提问作者Reyshawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:07:39