2012年12月18日 星期二

iOS - UI - Move Button

http://www.cocoanetics.com/2010/11/draggable-buttons-labels/



- (void)viewDidLoad 
{
    [super viewDidLoad];
 
 // create a new button
 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
 [button setTitle:@"Drag me!" forState:UIControlStateNormal];
 
 // add drag listener
 [button addTarget:self action:@selector(wasDragged:withEvent:) 
  forControlEvents:UIControlEventTouchDragInside];
 
 // center and size
 button.frame = CGRectMake((self.view.bounds.size.width - 100)/2.0,
   (self.view.bounds.size.height - 50)/2.0,
   100, 50);
 
 // add it, centered
 [self.view addSubview:button];
}
 
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
 // get the touch
 UITouch *touch = [[event touchesForView:button] anyObject];
 
 // get delta
 CGPoint previousLocation = [touch previousLocationInView:button];
 CGPoint location = [touch locationInView:button];
 CGFloat delta_x = location.x - previousLocation.x;
 CGFloat delta_y = location.y - previousLocation.y;
 
 // move button
 button.center = CGPointMake(button.center.x + delta_x,
  button.center.y + delta_y);
}

沒有留言:

張貼留言