如何使用Timer为UIView的宽度设置动画?

时间:2017-04-18 21:05:25

标签: swift uiview uiviewanimation animatewithduration

我有一个视图设置为我的视图宽度和一个计时器,在未来(在接下来的5分钟内)获得一些点。我的目标是将视图的宽度从view.width降低到0

我正在尝试

UIView.animate(withDuration: date.timeIntervalSinceNow, delay: 0, options: .curveEaseIn, animations: {
    self.countdownBar?.frame = CGRect(x: 0, y:self.view.frame.maxY - 3, width: 0, height: 3)
}, completion: nil)

但这会使countdownBar动画从视图顶部向下移动到maxY位置 - 而不是宽度

任何帮助将不胜感激!

修改:计时器代码

self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.countdownToCartExpiration), userInfo: nil, repeats: true)

countdownToCartExpiration中,我以分钟和秒的特定时间间隔进行一些UI更改

1 个答案:

答案 0 :(得分:3)

你应该使用像计时器或UIViewAnimation这样的东西。

如果您希望在5分钟内将console.log(JSON.stringify(data, null, '\t')); 缩小为width,那么您可以执行此类操作。

0

这假定视图是屏幕的整个宽度,并在300秒内将其设置为零。它还假设您没有使用AutoLayout来管理您的布局。如果您正在使用Autolayout,那么我们需要调整此值以更改约束而不是更改框架。

<强>更新

所以,因为你每秒钟都有一个计时器。我们仍然希望动画可能。如果计时器每隔30或60秒发射一次,那么我们可以调整框架,看起来很平滑。但每一秒都会看起来波涛汹涌。

var finalFrame = countdownBar!.frame
finalFrame.size.width = 0

UIView.animate(withDuration: 300, animations: {
    self.countdownBar?.frame = finalFrame
})

func countdownToCartExpiration (timer: Timer) { guard let countdownBar = countdownBar else { return } // Assuming you're already tracking currentTime somehow currentTime += timer.timeInterval var finalFrame = countdownBar.frame let totalTime = 300.0 finalFrame.size.width = view.frame.width * CGFloat(currentTime / totalTime) UIView.animate(withDuration: timer.timeInterval, delay: 0, options: [.beginFromCurrentState, .curveLinear], animations: { countdownBar.frame = finalFrame }, completion: nil) // ... Other stuff } 很重要,因为动画会发生重叠。 . beginFromCurrentState在这里非常重要,因为动画背靠背播放我们希望速度保持不变。

我假设你正在跟踪currentTime,这个动画的totalTime是300秒。但你可以明显调整。目标是将宽度设置为currentTime的百分比。