UIImageView 框架未按预期设置动画(大小和原点)

Tra*_*avo 5 animation uiview uiviewanimation ios swift

遇到了 UIView 帧动画问题。视图应该在原点和大小上设置动画,大小增加和原点线性移动以保持视图在同一位置。但是发生的情况是,视图减小到大小 (0,0),然后增加到仍然不是正确大小的大小。见附件视频。

问题视频:https : //media.pairby.com/I/u/a/IualExcJXn7CqLsGkcNZfwyEw5MKi3SV/v.mp4

func animateIn() {
  // Make _iconView large
  let w = bounds.width
  _iconView.frame = CGRect(
    x: frame.midX - w/2,
    y: frame.midY - w/2,
    width: w, height: w)

  isHidden = false

  UIView.animate(withDuration: 0.2, animations: {
    self.alpha = 1

    // Animate it smaller
    let w = self.bounds.width * 0.5
    self._iconView.frame = CGRect(
      x: self.frame.midX - w/2,
      y: self.frame.midY - w/2,
      width: w, height: w)
  })
}

func animateOut() {
  UIView.animate(withDuration: 3, delay: 0, options: .beginFromCurrentState, animations: {
    self.alpha = 0

    // Make it large again
    let w = self.bounds.width
    self._iconView.frame = CGRect(
      x: self.frame.midX - w/2,
      y: self.frame.midY - w/2,
      width: w, height: w)

  }, completion: { _ in self.isHidden = true })
}
Run Code Online (Sandbox Code Playgroud)

更多细节:

self 是 UIView 的一个子类,被限制为一个超视图。

_iconView 是一个 UIImageView

animateIn 保证在之前运行 animateOut

animateOut是没有按预期工作的功能,animateIn工作

Don*_*Mag 0

目前尚不完全清楚您需要做什么,但是......

  1. 您不需要首先更改大小 - 您可以简单地从当前状态为 _iconView 框架设置动画,并且

  2. 因为 _iconView 是的子视图self,所以您需要相对于边界而不是框架来定位它。

试试这样:

func doAnim() -> Void {     

    UIView.animate(withDuration: 3, delay: 0, options: .beginFromCurrentState, animations: {
        self.alpha = 0

        let s = self.bounds.width
        let halfS = s / 2

        self._iconView.frame = CGRect(
            x: self.bounds.midX - halfS,
            y: self.bounds.midY - halfS,
            width: s,
            height: s)

    })

}
Run Code Online (Sandbox Code Playgroud)