SudoPlz
SudoPlz

Reputation: 23333

Animating (moving) a UIView programmatically

Imagine having lot's of sibling views (i.e 20 sibling views) that you want to move around. You only want to change their x coordinates. The movements will be defined real time while the user is swiping their finger on the screen.

Is it ok to do that by changing their frame like so?

view.frame.origin.x += 5;

or is it too expensive performance wise?

Is there a more performant way to move all those views?

Upvotes: 0

Views: 209

Answers (1)

Jake G
Jake G

Reputation: 1195

That should be fine. Apple docs show that using a UIGestureRecognizer and updating a frame's center is a pretty standard way of moving views around.

Apple documentation on Pan Gesture.

Their example seems a little different then how I've seen it used, but general concept is the same. I would personally design it as such:

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
}

Upvotes: 1

Related Questions