通过UIPanGestureRecognizer移动View

今天尝试了下移动view,以前直接通过touch的事件弄过.现在用手势,更加方便.

网上别人的做法有直接改变,视图相对的原点坐标来做.代码上稍微复杂点,代码如下:

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];

[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:[piece superview]];

[piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
[gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}
}


- (void)adjustAnchorPointForGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
UIView *piece = gestureRecognizer.view;
CGPoint locationInView = [gestureRecognizer locationInView:piece];
CGPoint locationInSuperview = [gestureRecognizer locationInView:piece.superview];

piece.layer.anchorPoint = CGPointMake(locationInView.x / piece.bounds.size.width, locationInView.y / piece.bounds.size.height);
piece.center = locationInSuperview;
}
}

其实还有简单点的考虑,设置一个变量来保存下之前的坐标就更加容易理解:

CGPointpointLeftTop;

- (void)onPan:(UIPanGestureRecognizer *)pan

{

CGPoint p=[pan locationInView:self.superview];

if (pan.state==UIGestureRecognizerStateBegan) {

pointLeftTop=p;

}else if (pan.state==UIGestureRecognizerStateChanged) {

[self setFrame:CGRectMake(self.frame.origin.x+(p.x-pointLeftTop.x), self.frame.origin.y, self.frame.size.width, self.frame.size.height)];

pointLeftTop=p;

}else if (pan.state==UIGestureRecognizerStateEnded) {

NSLog(@"end");

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值