2011-07-18 35 views
0

這是我的代碼:iphone :: touchesMoved:在UIView中移動UIImageView?

- (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變量。

回答

1

我不太清楚你想要做什麼。我不知道爲什麼你把每個UIImageView's放在你放入視圖控制器視圖的UIView裏面。您也可以直接將UIImageView's作爲視圖控制器視圖的子視圖添加。

儘管如此,從我可以看出,它看起來像用戶必須能夠拖動屏幕上的圖像。

如果是這種情況,我建議您將UIImageView's中的每一個存儲在一個數組中。然後,在touchesBegan:withEvent:中,您將必須確定正在觸摸哪個UIImageView。在代碼中獲取代表主視圖中位置的CGPoint是一個好的開始。如果直接將UIImageView's添加爲主視圖的子視圖,則可以將此CGPoint的座標與這些UIImageView's的框架進行比較,以確定哪一個被按下。

然後,要允許拖動,您需要在觸摸開始時保存UIImageView的座標。然後,每次觸摸移動時,您都可以將UIImageView的新x位置計算爲原始x位置,再加上移動的距離。也就是說,

newImageViewX = imageViewStartX + (newTouchX - touchStartX);

同樣地,對於y位置。