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

标签 ios animation uiview observer-pattern

我想在使用 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/22582192/

相关文章:

ios - 使用 Cocoapods 在 Swift 中导入框架时出现问题

ios - 如何在 'aspect fill' 模式下将 UIImageView 裁剪为新的 UIImage?

android - 动画自定义对话框

iphone - 在推送 UINavigationController 时为 UIView 设置动画

ios - 创建圆圈并将其用作 "bar graph"

iphone - TTSearchTextFieldDelegate 不调用 textField :didSelectObject:

ios - 如何在 Core Data 中查找具有空关系的实体?

ios - 对 UIImageView 从起点到终点的移动进行动画处理

iphone - 在显示 UITabBar 之前显示 View

ios - 设置 UIView 的cornerRadius 时如何防止 subview 被剪切?