您的位置:首页 > 产品设计 > UI/UE

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

2016-02-29 16:36 399 查看
最近做了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];

}

通过加入上面的代码,就可以实现图片的拖动了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: