2011-02-24 69 views
0

我嘗試在iPhone應用程序中拖放多個圖像。我在YouTube上看過一個教程,但它不起作用。IOS:拖動多個圖像

我創建的圖像是這樣的:

image1=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_klein.png"]]; 
[image1 setFrame:CGRectMake(touchPoint.x-25,touchPoint.y-25,50,50)]; 
[[self view] addSubview:image1]; 

image2=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button2_klein.png"]]; 
[image2 setFrame:CGRectMake(135,215,50,50)]; 
[[self view] addSubview:image2]; 

然後我試圖讓他們dragable這樣:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *myTouch = [[event allTouches] anyObject]; 
    CGPoint location = [myTouch locationInView:self.view]; 

    if ([myTouch view] == image1) { 
     image1.center = location; 
     NSLog(@"Test1"); 
    } 
    if ([myTouch view] == image2) { 
     image2.center = location; 
     NSLog(@"Test2"); 
    } 
} 

但doesn't工作。當我試圖讓一個圖像可拖動時,它就起作用了。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *myTouch = [[event allTouches] anyObject]; 
    image1.center = [myTouch locationInView:myTouch.view]; 
} 

有人可以告訴我,問題在哪裏?

回答

-3

image1image2UIImageView S,您可以在針對[(UITouch*) view]不能比擬的(這是一個UIView)。所以比較從未發生,這意味着兩個if條件不會被覆蓋。

嘗試把image1image2內2層UIView的named image1Viewimage2View,你的代碼會變得if ([myTouch view]==image1View) image1View.center=location等。 。

+3

當然可以。 UIImageView是UIView的子類,當然,您可以將任何指針與任何其他指針進行比較。 「比較從未發生」從未發生過。 – 2011-06-20 01:40:43

+0

是的,你可以比較指針。 – boudini 2011-07-28 10:15:52

1

UITouch.view返回的「處理」觸摸視圖(或多或少-hitTest:withEvent:返回認爲在這種情況下,它是self,不image1image2(您可以通過設置斷點-touchesMoved檢查此:withEvent:方法和。檢查觸摸自己)

你要像做

if ([image1 pointInside:[myTouch locationInView:image1] withEvent:event]) { 
    ... 
} else if ([image2 pointInside: ...]) { 
    ... 
} 

注意,觸摸既可以是內部的意見;我已經默認選擇此搜索處理這個,但你會必須決定什麼是「正確」。