0

我是全新的觸摸和拖動,我試圖製作八個可拖動的圖像。下面是它看起來像在我ViewController.m文件:在iOS中拖動多個圖像

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

    //check for which peg is touched 

    if ([touch view] == darkGreyPeg){darkGreyPeg.center = location;} 
    else if ([touch view] == brownPeg){brownPeg.center = location;} 
    //there are six more else ifs 
} 

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

    [self touchesBegan:touches withEvent:event]; 

} 

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [self ifCollided]; 

} 

如果我拿出if語句,以及locationInView:self.view到locationInView:touch.view,我能夠左右拖動darkGreyPeg沒有問題,並在適當的時候觸發我的[ifCollided]。

我正在看一個youTube教程(Milmers Xcode教程,「拖動多個圖像」),他有完全相同類型的代碼,而我的工作不起作用。任何人都可以向我指出爲什麼?

謝謝。

回答

0

你不應該在你的ViewController中實現這些方法,而是在你希望能夠拖動的視圖類中。

+0

你能解釋一下嗎?我不是個聰明人。 – novalsi

0

我認爲這個問題是用==來比較對象:

[touch view] == darkGreyPeg 

您應該使用isEqual:方法來比較對象:

[[touch view] isEqual:darkGrayPeg] 

編輯後:我認爲問題是,您忘記爲圖像視圖設置userInteractionEnabled爲YES。如果不這樣做,touch.view將是超級視圖,而不是圖像視圖。此外,你可能並不需要所有這些if語句來決定要移動的圖像視圖,你可以用touch.view:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    UITouch *touch = [[event allTouches] anyObject]; 
    CGPoint location = [touch locationInView:self.view]; 
    if (![touch.view isEqual:self.view]) touch.view.center = location; 
} 

如果您有其他意見,除了self.view,你不想要移動,那麼您必須也排除它們,或者使用不同的排除條件(例如,如果它是圖像視圖或只有具有特定標記值的對象,才移動該對象)。

+0

這不能解決問題。 – novalsi

+0

@novalsi,對不起,這沒有幫助,但你應該使用這種方法。通過使用==,你正在比較指針,而不是對象本身。根據你如何得到對象的引用,有時候指針比較起作用,有時不起作用。 – rdelmar

+0

@novalsi,我更新了我的答案,我認爲你的問題是。 – rdelmar

1

嘗試檢查用戶交互啓用&多次觸摸您的視圖圖像屬性。如果沒有檢查啓用的用戶交互,您不能使用多個拖動。我嘗試了這一點,併成功拖動多個圖像,標籤或按鈕。