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/48142182/

相关文章:

angularjs - Angular Animate 1.4 太快了

javascript - 如何在点击时触发第二个动画

android - Android上 View 背景颜色的动画变化

ios - 如何在 Swift 中以编程方式更改自定义 UITableViewCell 中按钮的背景颜色?

iOS - UIImagePickerController 在设备上崩溃

iphone - 如何在 ios 中加载 wfm(线框)

ios - "Stack"UIViewController 中的 UIViews (iOS 7)

ios - 在 Swift 中平滑展开 UIView 动画

ios - 如何让在旧版 Xcode 中构建的应用程序同时支持 32 位和 64 位?

iphone - 重新加载表格 View 后,表格 View 中标签中的先前文本正在显示