一 移动的button
- (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);
}
二 移动的label
- (void)viewDidLoad
{
[super viewDidLoad];
// create a label
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]
autorelease];
label.text = @"Drag me!";
// enable touch delivery
label.userInteractionEnabled = YES;
UIPanGestureRecognizer *gesture = [[[UIPanGestureRecognizer alloc]
initWithTarget:self
action:@selector(labelDragged:)] autorelease];
[label addGestureRecognizer:gesture];
// add it
[self.view addSubview:label];
}
- (void)labelDragged:(UIPanGestureRecognizer *)gesture
{
UILabel *label = (UILabel *)gesture.view;
CGPoint translation = [gesture translationInView:label];
// move label
label.center = CGPointMake(label.center.x + translation.x,
label.center.y + translation.y);
// reset translation
[gesture setTranslation:CGPointZero inView:label];
}