2013-02-14 37 views
0

我已經通過很多教程了在屏幕上拖動圖像使用touchesmoved方法 但拖動態創建的UIImageView他們大多不是用於動態創建imageviews如何在OBJ C(Xcode中)

在項目中,我創建5的UIImageView編程,

現在我想,用戶可以拖動屏幕上的>>我也遵循這個答案 Question但一切都是徒勞,沒有成功,到目前爲止>

用於創建動態的ImageView代碼

for (int i = 0; i < index ; i++) 
{ 
UIImageView *imageView1 = [[UIImageView alloc] initWithImage: 
[UIImageimageNamed:image_name]];   
self.imageView1.userInteractionEnabled = YES; 
imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f); 
self.view.userInteractionEnabled = YES; 
[self.view addSubview:imageView1]; 
} 

提前感謝好答覆

回答

0

我對你如何創建UIImageViews有點困惑,因爲你正在使用for-loop而不是靜態名稱。所以你可能有15個名爲「imageView1」的UIImageView。 但無論如何,如果您在鏈接到的問題中使用代碼,則完全沒有關係。也許你把這些線路排除在外......這是正確的順序。 (如果它不工作讓我知道,隨着錯誤你)

//-(void)ViewDidLoad? {???? is this your function?? 
    int xvalue = 0;//?? not sure where you declared these 
    int yvalue = 0;//?? not sure where you declared these 
    for (int i = 0; i < index ; i++) { 
     UIImageView *imageView1 = [[UIImageView alloc] initWithImage: 
     [UIImageimageNamed:image_name]];   
     self.imageView1.userInteractionEnabled = YES; 
     imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f); 
     self.view.userInteractionEnabled = YES; 
     [self.view addSubview:imageView1]; 
    } 

    self.elements=[myElements getElements]; 
    imagesElements = [[NSMutableArray alloc]init]; 
    for(ElemetsList *item in self.elements) { 
      UIImageView *oneelement = [[UIImageView alloc] initWithImage:[UIImage imageNamed:item.imgElement]]; 
      oneelement.frame = CGRectMake(item.positionX, item.positionY, item.width, item.height); 
      oneelement.userInteractionEnabled=YES; 
      [imagesElements addObject:oneelement]; 
    } 

    for(UIImageView *img in imagesElements) { 
     [self.view addSubview:img]; 
    } 
//}? End Function, whatever it may be...? 

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [[event allTouches] anyObject]; 

    for(UIImageView *img in imagesElements) 
    { 
     if([self view] == img) 
     { 
      CGPoint location = [touch locationInView:self.view]; 
      img.center=location; 
     } 
    } 
} 

如果你只是想硬編碼爲一個圖像移動試試這個:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    UITouch *touch = [[event allTouches] anyObject]; 
    imageView1.center=[touch locationInView:self.view]; 
} 
+0

我有嘗試了上面更正的代碼>>只有for循環內部的行>>但還沒有工作 – 2013-02-14 13:01:31

+0

你只嘗試了代碼裏面for(int i = 0; i 2013-02-14 13:03:54

+0

我已經使用touchesmoved方法,但程序無法進入所需的活動>> 告訴我self.elements代碼的目的以及在哪裏添加此? – 2013-02-14 13:06:08

0

有很多方法可以解決這個問題。您可以在創建時向每個UIImageView添加UIPanGestureRecognizer,也可以使用touchesBegan :, touchesMoved:on self(假設它是UIViewController)並遍歷每個UIImageView以查看其幀是否包含觸摸點。