0
点赞
收藏
分享

微信扫一扫

按钮拖动

云竹文斋 2023-02-15 阅读 64


@implementation ViewController{
UIButton* btn;
CGPoint lastPoint;
}

- (void)viewDidLoad {
[super viewDidLoad];

[super viewDidLoad];
btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setBackgroundColor:[UIColor blackColor]];
btn.frame = CGRectMake(10, 10, 150, 50);

[btn setTitle:@"拖动" forState:UIControlStateNormal];

UIPanGestureRecognizer* movePress = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragButton:)];
[btn addGestureRecognizer:movePress];

[self.view addSubview:btn];
}

- (void)dragButton:(UILongPressGestureRecognizer *)sender{
CGPoint point = [sender locationInView:self.view];

switch (sender.state) {
case UIGestureRecognizerStateBegan:
lastPoint = point;
break;
case UIGestureRecognizerStateChanged:{
CGFloat offX = point.x - lastPoint.x;
CGFloat offY = point.y - lastPoint.y;
[btn setCenter:CGPointMake(btn.center.x + offX, btn.center.y + offY)];
lastPoint = point;
}
break;
}
}

举报

相关推荐

0 条评论