在我的代码中,我有一个对象数组,这些对象是带有UIImages的UIImageViews。
我在-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
中使用for循环来逐个移动数组中的所有对象。
一旦将它们移动到主视图上的不同位置,我希望能够抓住任何这些对象并将它们移动到其他位置。
我不确定如何做到最好。有没有办法可以使用touchesbegin,这样我只能拖动我点击的项目?
基本上,现在有五个UIImageViews,每个都有UIImage,我试图达到这样的程度,当我点击它们中的任何一个时,它们都可以移动。
答案 0 :(得分:2)
//UIDraggableImageView.h
#import <UIKit/UIKit.h>
@interface UIDraggableImageView : UIImageView
{
CGPoint currentPoint;
}
@end
//UIDraggableImageView.m
#import "UIDraggableImageView.h"
@implementation UIDraggableImageView
- (id)initWithImage:(UIImage *)image
{
if (self = [super initWithImage:image]) {
self.userInteractionEnabled = YES;
}
return self;
}
-(void)dealloc {
[super dealloc];
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// When a touch starts, get the current location in the view
currentPoint = [[touches anyObject] locationInView:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Get active location upon move
CGPoint activePoint = [[touches anyObject] locationInView:self];
// Determine new point based on where the touch is now located
CGPoint newPoint = CGPointMake(self.center.x + (activePoint.x - currentPoint.x),
self.center.y + (activePoint.y - currentPoint.y));
//--------------------------------------------------------
// Make sure we stay within the bounds of the parent view
//--------------------------------------------------------
float midPointX = CGRectGetMidX(self.bounds);
// If too far right...
if (newPoint.x > self.superview.bounds.size.width - midPointX)
newPoint.x = self.superview.bounds.size.width - midPointX;
else if (newPoint.x < midPointX) // If too far left...
newPoint.x = midPointX;
float midPointY = CGRectGetMidY(self.bounds);
// If too far down...
if (newPoint.y > self.superview.bounds.size.height - midPointY)
newPoint.y = self.superview.bounds.size.height - midPointY;
else if (newPoint.y < midPointY) // If too far up...
newPoint.y = midPointY;
// Set new center location
self.center = newPoint;
}
@end
答案 1 :(得分:1)
我在可拖动视图中使用UIPanGestureRecognizer
取得了类似的成功。要连接它,它可能看起来像这样:
@implementation DraggableView
-(id)initWithFrame:(CGRect)frame
{
...
...
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)] autorelease];
[self addGestureRecognizer:panGesture];
..
return self;
}
@end
在pan:
方法中,您可以检查手势的状态,甚至捕捉手势的位置并使用它来重新定位视图。这是一个 粗略 示例:
-(void)pan:(UIPanGestureRecognizer *)gesture
{
if (gesture.state==UIGestureRecognizerStateChanged)
{
//We're moving!
UIView *aRootView = <perhaps your root view controller's view>;
CGPoint currentOrigin = [gesture translationInView:aRootView];
self.frame = CGRectMake(currentOrigin.x,currentOrigin.y,self.frame.size.width,self.frame.size.hight);
...
...
}
}
UIPanGestureRecognizer
上的
答案 2 :(得分:0)
您可能需要考虑为要移动的视图添加手势识别器,这样您就可以轻松判断它们何时被轻击,并且您可以使用touchesMoved来移动它们...
答案 3 :(得分:-1)
在按钮上单击将相机胶卷中的图像添加到imageview。图像可以放大和缩小,并应将该图像拖动到视图中的任何位置。