在Swift中使用UIView.animateWithDuration增加参数

3

我有一个按钮的IBOutlet集合,我想按顺序逐个呈现在屏幕上。它们都很好地从屏幕外开始,但当它们动画进入时,我希望每个按钮在前一个按钮之后0.05秒呈现在屏幕上。我无法弄清如何在UIView.animateWithDuration中增加延迟。使用下面的代码,它们都同时在屏幕上进行动画。

//outlet collection
@IBOutlet var options: [UIButton]!

let increment = 0.25

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    for button in options {
        button.center.y += view.bounds.height
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    for button in options {
        UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
            button.center.y -= self.view.bounds.height
            self.increment + 0.05
            }, completion: nil)
    }
}
3个回答

1
for button in options {
        UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
            button.center.y -= self.view.bounds.height
            }, completion: nil)

    }
           increment = increment + 0.05

}

此外:

除此之外: 更改此内容

let increment = 0.25

   var increment = 0.25

增加动画之外的增量。由于animateWithDuration是异步方法,它会先返回。因此,所有按钮的延迟时间相同。

感谢您的输入。不知何故,它仍然无法正常工作。我按照您的建议将增量移出了动画,但所有按钮仍然一起在屏幕上进行动画。我也将所有内容移至viewDidAppear并尝试了一下,但仍然无法正常工作。 - Nacho

0
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!

@IBOutlet var options: [UIButton]!

let increment = 0.25


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    for button in options {
        button.center.y += view.bounds.height

    }
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

        for button in options {
            UIView.animateWithDuration(1.0, delay: increment, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
                button.center.y -= self.view.bounds.height
                }, completion: nil)

            self.increment + 0.05
    }
}

在编程中,当使用+=时出现错误“无法调用类型为'(Double, FloatLiteralConvertible)'的参数列表”,但只需使用+即可。

如果你将一个属性设置为 let,那么它就不能被改变。请查看我的更新。 - Leo
你应该编辑你的问题,而不是将这个作为答案添加 - 这不是一个答案。 - jrturton
成功了!我一直以为是for循环写错了,但完全忽略了常量。谢谢@jrturton,第一次发帖,感谢提醒。 - Nacho

-1

这里是实现动画之间所需延迟的方法:

var i! as UInt64;
i = 0
for button in options {
                // your animation with delay
        UIView.animateWithDuration(1.0, delay: (i *0.05), usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: {
            button.center.y -= self.view.bounds.height
            }, completion: nil)
    })
    ++i

}

动画方法中已经有一个“delay”参数,你为什么还要用GCD来搞这个? - jrturton

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