How would I allow the user to reposition a UIView object?

How would I allow the user to move a UIView object using a long press so that he could reposition the UIView?

Replies

I would suggest doing a Google search for "drag uiview gesture". There are quite a few examples.


Some of those tutorials actually perform the move by adjusting the view's center or frame property, which of course doesn't work with auto layout. It's fine if you're not using constraints for that view, but personally I prefer to use auto layout and update constraint constants instead. You can also update the transform property (normally done temporarily, e.g. while the drag is in progress; usually you would use a more "permanent" way to "finalize" the move once the gesture ends, such as updating the constraint constants).

Use a UILongPressGestureRecognizer and in the delegate method, use the transform property of your UIView with your touch.location(in view: UIView) to move the view. Don't forget to set the transform proptery to .identity when the gesture recognizer completes.


You can watch the Auto Layout techniques from the WWDC2017 here : https://developer.apple.com/videos/play/wwdc2017/412/(look at "Tracking touch")