gpt4 book ai didi

ios - 在动画期间观察 UIView 框架的变化

转载 作者:行者123 更新时间:2023-11-28 07:55:42 30 4
gpt4 key购买 nike

我想在使用 animateWithDuration:delay:options:animations:completion: 设置动画时观察 UIView 原点 x 坐标的变化。我想在这个动画期间以粒度级别跟踪 x 坐标的变化,因为我想改变与正在动画的 View 可能接触的另一个 View 的交互。我想在确切的接触点进行更改。我想了解在更高层次上执行此类操作的最佳方法:

-- 我应该在联系点的完成回调中使用 animateWithDuration:... 吗?换句话说,第一个动画一直运行到它到达那个 x 坐标,然后动画的其余部分发生在完成回调中?

-- 我应该使用 NSNotification 观察器并观察 frame 属性的变化吗?这有多准确/精细?我可以跟踪对 x 的每个更改吗?我应该在单独的线程中执行此操作吗?

欢迎任何其他建议。我正在寻找最佳实践。

最佳答案

使用 CADisplayLink 因为它是专门为此目的构建的。在文档中,它说:

Once the display link is associated with a run loop, the selector on the target is called when the screen’s contents need to be updated.

对我来说,我有一个填满的条,当它超过某个标记时,我必须更改该标记上方 View 的颜色。

这是我做的:

let displayLink = CADisplayLink(target: self, selector: #selector(animationDidUpdate))
displayLink.frameInterval = 3
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)

UIView.animateWithDuration(1.2, delay: 0.0, options: [.CurveEaseInOut], animations: {
self.viewGaugeGraph.frame.size.width = self.graphWidth
self.imageViewGraphCoin.center.x = self.graphWidth
}, completion: { (_) in
displayLink.invalidate()
})

func animationDidUpdate(displayLink: CADisplayLink) {
let presentationLayer = self.viewGaugeGraph.layer.presentationLayer() as! CALayer

let newWidth = presentationLayer.bounds.width

switch newWidth {
case 0 ..< width * 0.3:
break
case width * 0.3 ..< width * 0.6:
// Color first mark
break
case width * 0.6 ..< width * 0.9:
// Color second mark
break
case width * 0.9 ... width:
// Color third mark
break
default:
fatalError("Invalid value observed. \(newWidth) cannot be bigger than \(width).")
}
}

在示例中,我将 frameInterval 属性设置为 3,因为我不必严格更新。默认值为 1,这意味着它会为每一帧触发,但会影响性能。

关于ios - 在动画期间观察 UIView 框架的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48142182/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com