IOS_可移动的UIImageView(随手指移动)

来源:互联网 发布:淘宝直播怎么介绍自己 编辑:程序博客网 时间:2024/05/01 23:53

最近做了2个项目,都是跟UIImageView的图片拖动有关。

其实这个方法很好实现。可以自己子类化一个UIImageView类。然后设置这个子类能够响应交互行为。

再在touches事件中去处理拖动事件,设置新的frame。

示例代码:

先设置

aniImgView.image = img; //aniImgView是UIImageView实例

aniImgView.userInteractionEnabled = YES; //设置响应交互行为,默认是no

再处理touches事件:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

    // Retrieve the touch point

    beginPoint = [[touches anyObject] locationInView:self]; //记录第一个点,以便计算移动距离

 

    if ([self._delegate respondsToSelector: @selector(animalViewTouchesBegan)]) //设置代理类,

在图像移动的时候,可以做一些处理

    [self._delegate animalViewTouchesBegan];

}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {

    // Move relative to the original touch point

   // 计算移动距离,并更新图像的frame

    CGPoint pt = [[touches anyObject] locationInView:self];

    CGRect frame = [self frame];

    frame.origin.x += pt.x - beginPoint.x;

    frame.origin.y += pt.y - beginPoint.y;

    [self setFrame:frame]; 

    if ([self._delegate respondsToSelector: @selector(animalViewTouchesMoved)])

    [self._delegate animalViewTouchesMoved];

}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

   if ([self._delegate respondsToSelector: @selector(animalViewTouchesEnded)])

   [self._delegate animalViewTouchesEnded];

}


通过加入上面的代码,就可以实现图片的拖动了。

0 0