1

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...

Popularity: 3%

  1. Niranjan says:

    Hey Thnkx….!!
    It Works.!!

More in iOS (48 of 55 articles)