iOS: a draggable UIButton

I started implementing my own scrolling UI for a control and I never attempted something like a draggable custom bit of UI in iOS before. If you’re interested, read along. My implementation is a first pass and it’s pretty simple. When you’ve come from an AS3 world it might not feel so simple until you see the solution however.

I created a custom UIButton in my .xib file and hooked it up in code. I gave it an instance name of dragButton.

In my code (.m) I created a selector for the button:

[dragButton addTarget:self action:@selector(draggedOut:withEvent:)
    forControlEvents:UIControlEventTouchDragOutside |
    UIControlEventTouchDragInside];

The delegate method:

- (void) draggedOut: (UIControl *) c withEvent: (UIEvent *) ev {
    CGPoint point = [[[ev allTouches] anyObject] locationInView:self.view];    
    if(point.y > 120 && point.y <366)
        c.center = CGPointMake(237, point.y - c.bounds.size.height/2 -5);
}

I needed to constrain my UIButton to an x position so it only moved vertically. There are more elegant approaches to the constraint, but for now this is working pretty well. I can drag it up and down in it’s view and it won’t go beyond my designated positions.

Simple yet effective.

Related Posts Plugin for WordPress, Blogger...

One thought on “iOS: a draggable UIButton

Leave a Reply

Your email address will not be published. Required fields are marked *


× 9 = thirty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>