如果要要button能夠移動(dòng),有兩種辦法
一:這種辦法能移動(dòng),但暫時(shí)我還不能讓它移動(dòng)裳食,addTarget方法也沒用。
方法失效:
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
能移動(dòng):
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
//當(dāng)前的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);
}
二:這種辦法能移動(dòng)线椰,也能點(diǎn)擊
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[btn addGestureRecognizer:pan];
點(diǎn)擊事件有用:
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
移動(dòng):
- (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]];
}