以编程方式动画(移动)UIView

Animating (moving) a UIView programmatically

想象一下,您有很多想要移动的兄弟视图(即 20 个兄弟视图)。 您只想更改它们的 x 坐标。 当用户在屏幕上滑动手指时,将实时定义动作。

像这样改变他们的框架可以吗?

view.frame.origin.x += 5;

还是性能太贵了?

是否有更高效的方式来移动所有这些视图?

那应该没问题。 Apple 文档表明,使用 UIGestureRecognizer 并更新框架的中心是一种非常标准的移动视图的方式。

Apple documentation on Pan Gesture.

他们的示例似乎与我看到的使用方式略有不同,但总体概念是相同的。我个人会这样设计:

func viewDidLoad() {
    let panGesture = UIPanGestureRecognizer(target: self, action: Selector("didDrag:"))
    moveableView.addGestureRecognizer(panGesture)
}

func didDrag(gesture: UIPanGestureRecognizer) {
    let translation = gesture.translationInView(self.view)
    customView.center.x = customView.center.x + translation.x // Customize this.
    customView.center.y = customView.center.y + translation.y
}