Tuesday, 19 October 2010

moveable UIView example

I was hoping to find a very quick example to for enabling a UIView to be moved using simple touch but didn't. In the end I worked it out for myself and thought I'd share. It's actually just a few lines of code. Subclass UIView and make sure that userInteractionEnabled is set to YES and then add this to your subclass:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];
CGPoint last = [touch previousLocationInView:self.superview];
CGPoint current = [touch locationInView:self.superview];
CGPoint translate = CGPointMake(last.x - current.x, last.y - current.y);
self.center = CGPointMake(self.center.x - translate.x, self.center.y - translate.y);
[self.superview bringSubviewToFront:self];

}

Voila! Your UIView can now be moved around.


No comments: