I'm trying to do something new with my app.
I have a number of buttons that I'd like the user to be able to rearrange on the screen by dragging them. The view is currently created via Interface Builder. The ideal implementation would check for a flag in NSUserDefaults which if present would allow the user to move the object, drop it,then remove the flag which would save the setup for next time the user loads.
Anyone know if anything like this would be possible?
There is some open sourced code that does exactly that.
https://github.com/gmoledina/GMGridView
"A performant Grid-View for iOS (iPhone/iPad) that allows sorting of views with gestures (the user can move the items with his finger to sort them) and pinching/rotating/panning gestures allow the user to play with the view and toggle from the cellview to a fullsize display."
Since
UIControl
is aUIView
, you can useaddGestureRecognizer
to install on you object aUIPanGestureRecognizer
.A
UIGestureRecognizer
allows a function you wrote to be called each time the specific gesture is executed on the view you attach the gesture recognizer to. You create one like this in your view controllerviewDidLoad
method:This code will instantiate a gesture recognizer and attach it to your button. So, every gesture of kind "pan" (dragging) done on the button will cause a call to
handleDragOnButton
. In the code above, I assume that you your view controller contains declarations like:Now, you need define a
handleDragOnButton
in your controller. In this function, you can get the current touch and move the button accordingly by changing itsframe
.Don't forget to
release
the gesture recognizer in the controller'sdealloc
.Look also at this doc from Apple.
An alternative could be using
UIResponder
'sbut I would only suggest that if you are targeting iOS 3.1.3 and older.
You can have it done by using the action method -
//called on each instance during a drag event