如果要要button能够移动,有两种办法
一:这种办法能移动,但暂时我还不能让它移动,addTarget方法也没用。
方法失效:
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
能移动:
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
//当前的point
CGPoint currentP = [touch locationInView:self];
//以前的point
CGPoint preP = [touch previousLocationInView:self];
//x轴偏移的量
CGFloat offsetX = currentP.x - preP.x;
//Y轴偏移的量
CGFloat offsetY = currentP.y - preP.y;
self.transform = CGAffineTransformTranslate(self.transform, offsetX, offsetY);
}
二:这种办法能移动,也能点击
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[btn addGestureRecognizer:pan];
点击事件有用:
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
移动:
- (void)pan:(UIPanGestureRecognizer *)recognizer{
CGPoint translation = [recognizer translationInView:[self superview]];
CGPoint newCenter = CGPointMake(recognizer.view.center.x+ translation.x,
recognizer.view.center.y + translation.y);// 限制屏幕范围:
newCenter.y = MAX(recognizer.view.frame.size.height/2, newCenter.y);
newCenter.y = MIN([self superview].frame.size.height - recognizer.view.frame.size.height/2, newCenter.y);
newCenter.x = MAX(recognizer.view.frame.size.width/2, newCenter.x);
newCenter.x = MIN([self superview].frame.size.width - recognizer.view.frame.size.width/2,newCenter.x);
recognizer.view.center = newCenter;
[recognizer setTranslation:CGPointZero inView:[self superview]];
}