iphone::touchesMoved:是否将UIImageView移动到UIView中?

iphone::touchesMoved:是否将UIImageView移动到UIView中?,uiview,uiimageview,drag,Uiview,Uiimageview,Drag,这是我的代码: - (void) touchesBegan: (NSSet *)touches withEvent: (UIEvent *)event { CGPoint pt = [[touches anyObject] locationInView:self.view]; startLocation = pt; [super touchesBegan: touches withEvent: event]; } -(void)touchesMoved:(NSSet *)touches wi

这是我的代码:

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

CGPoint pt = [[touches anyObject] locationInView:self.view];
startLocation = pt;
[super touchesBegan: touches withEvent: event];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt = [[touches anyObject] locationInView:self.view];
CGRect frame = [self.view frame];
frame.origin.x += pt.x - startLocation.x;
frame.origin.y += pt.y - startLocation.y;
[self.view setFrame:frame];
}


- (void)viewDidLoad
{
[super viewDidLoad];

UIView *v = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)];
v.backgroundColor = [UIColor redColor];


UIImageView *imv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]];
imv.frame = CGRectMake(0, 0, 50, 50);
[v addSubview:imv];

[self.view addSubview: v];
[v release];

UIView *v2 = [[UIView alloc] initWithFrame: CGRectMake(100, 100, 100, 100)];
v2.backgroundColor = [UIColor blueColor];


UIImageView *imv2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"boo2.png"]];
imv2.frame = CGRectMake(0, 0, 50, 50);
[v2 addSubview:imv2];

[self.view addSubview: v2];
[v2 release];
}
我要做的是将UIImageView移动到UIView内部,而不是整个视图。但是,上面的代码,当我尝试拖动时,它会移动整个视图


注意:图像是从其他函数返回的,未在viewdidload中声明。假设您不能声明UIImageView变量。

我不太确定您想做什么。我不知道为什么要将每个
UIImageView的
放在一个
UIView
中,并将其放在视图控制器的视图中。您也可以直接将
UIImageView的
添加为视图控制器视图的子视图

然而,从我所能看出,用户必须能够在屏幕上拖动图像

如果是这种情况,我建议您将
UIImageView的每个
存储在一个数组中。然后,在触摸开始:withEvent:中,您必须确定正在触摸哪个
UIImageView
。在主视图中获取表示位置的
CGPoint
,就像在代码中一样,这是一个好的开始。如果将
UIImageView的
直接添加为主视图的子视图,则可以将此
CGPoint
的坐标与这些
UIImageView的
帧进行比较,以确定按下的是哪一个

然后,要允许拖动,需要在触摸开始时保存
UIImageView
的坐标。然后,每次触摸移动时,您都可以将
UIImageView
的新x位置计算为原始x位置加上移动的距离。就是

newImageViewX=imageViewStartX+(newTouchX-touchtstartx)

对于y位置也是如此