UIView animateWithDuration速度过快

7

我在下面的代码中使用了UIView animateWithDuration来增加shapeLayer.frame.size.height,但无论持续时间如何,它都会快速动画。我发现一些帖子推荐使用一些延迟时间,我已经这样做了,但它仍然非常快地动画,并忽略我设置的5秒持续时间。

private let minimalHeight: CGFloat = 50.0  
private let shapeLayer = CAShapeLayer()

override func loadView() {  
super.loadView()

shapeLayer.frame = CGRect(x: 0.0, y: 0.0, width: view.bounds.width, height: minimalHeight)
shapeLayer.backgroundColor = UIColor(red: 57/255.0, green: 67/255.0, blue: 89/255.0, alpha: 1.0).CGColor
view.layer.addSublayer(shapeLayer)

  }

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}


override func viewDidAppear(animated: Bool) {
   delay(3)    {

    UIView.animateWithDuration(5.0) {
        self.shapeLayer.frame.size.height += 400.0
        }
    }

如何使动画在5秒内完成?
4个回答

2

试一试:

override func viewDidAppear(_ animated: Bool) {
    //You should not edit directly the frame here, or the change will be committed ASAP. Frame does not act like constraints.
    // create the new frame
    var newFrame = self.shapeLayer.frame
    newFrame.size.height += 400.0

    UIView.animate(withDuration: 5.0, delay: 3.0, options: .curveEaseOut, animations: {
        //assign the new frame in the animation block
        self.shapeLayer.frame = newFrame
    }, completion: { finished in

    })
}

我尝试了上面的代码,但动画仍然非常快。 - Jickery
动画是非常快还是没有动画? - Pipiks
1
基本上,它在不到一秒的时间内就从原始位置移动到了目标位置。这就是我说动画非常快的原因。 - Jickery
也许答案在这里。 - Pipiks
链接中的第二种方法是我最初所做的。 - Jickery
显示剩余2条评论

2
也许你应该尝试使用 CABasicAnimation
    let fromValue = view2.layer.bounds.height
    let toValue = view2.layer.bounds.height + 50
    CATransaction.setDisableActions(true) //Not necessary
    view2.layer.bounds.size.height = toValue
    let positionAnimation = CABasicAnimation(keyPath:"bounds.size.height")
    positionAnimation.fromValue = fromValue
    positionAnimation.toValue = toValue
    positionAnimation.duration = 1
    view2.layer.addAnimation(positionAnimation, forKey: "bounds")

谢谢,它正在工作,但我真的很想知道为什么 animateWithDuration 不起作用。 - Jickery
1
因为您正在使用适用于UIView的动画方法。您正在尝试对CALayer进行动画处理,而它是一个较低级别的组件。 - CZ54
如果您能帮我看一下这个SO问题,我会非常感激 http://goo.gl/iqSmQq,我一直没有取得任何进展。 - Jickery

0
  1. 不要将更改放在动画块内,而是在动画之前进行更改。

  2. 然后,在动画中,只调用superView.layoutIfNeeded()。

这对我很有效,参考:如何动画化约束变化?


0
在我的情况下,问题是代码的其他地方禁用了动画: [UIView setAnimationsEnabled:false]; 将其更改为true解决了问题: [UIView setAnimationsEnabled:true];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接