2014-03-27 31 views
0

我正在開發棋盤遊戲,並且我的棋盤上有10x10個單元格,每個單元格都是由UIImageView拍攝的,所以當玩家試圖將棋子放入單元格時,相應的單元格應設置爲圖像。拖動圖像並放入正確的邊界框

我想要實現的是,當用戶拖動一塊並嘗試將其放到板上時,該塊應該適合單元格的UIImageView。現在的問題是我可以把棋子放在棋盤上的任何地方,甚至在兩個單元之間。我能做些什麼來解決它?感謝

----------------更新時間:----------------

因爲我所做的一切故事板,所以我可以分享兔子的代碼很少。我有以下的代碼行中h文件:

@property(retain) IBOutletCollection(UIImageView) NSArray *images; 

它們的UIImageView的長度爲100的陣列,它們中的每一個對應於一個細胞中板,如下所示:

enter image description here

當前板上的圖標是自動生成的,我想要拖到板上的目標圖標位於板的左上角('X'圖標)。和下面的方法,可處理拖動:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { 
    CGPoint translation = [recognizer translationInView:self.view]; 
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
             recognizer.view.center.y + translation.y); 
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view]; 
} 

現在的問題是我可以把「X」的任何地方在黑板上,如下所示:

enter image description here而是我希望把它適合進入董事會的一個單元格。

+0

請分享一些代碼。沒有代碼,我們不能說爲什麼會發生這種情況。 – Rashad

+0

設置UIImageView內容屬性。你能分享你的代碼集嗎? –

回答

1

可以通過檢測翻譯已經結束,其細胞達到這個例如:

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { 
     CGPoint translation = [recognizer translationInView:self.view]; 
     CGPoint origin = yourGrid.frame.origin; //where yourGrid refers to the main game board 
     float cellHeight = 30; //enter the corresponding value for cellHeight and cellWidth 
     float cellWidth = 30; //I've chosen 30 as an arbitrary value. 
     int translationXIndex = (recognizer.view.center.x + translation.x - origin.x)/cellWidth; 
     int translationYIndex = (recognizer.view.center.y + translation.y - origin.y)/cellHeight; 

//Assuming you count left to right and then up to down 
     [[images objectAtIndex: (translationXIndex + (10*translationYIndex))] setImage:[UIImage imageNamed:@"YourImage.png"]]; 
     recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
              recognizer.view.center.y + translation.y); 
     [recognizer setTranslation:CGPointMake(0, 0) inView:self.view]; 
     //You would have to remove the object you just dragged now, since you've changed the image of the corresponding cell 
     } 

如何工作的:識別器查找翻譯中心並找出它位於其內的細胞。然後訪問該單元格的imageView並將圖像更改爲目標圖像。

希望這會有所幫助。

+0

最後,我使用每個uiimageview的中心作爲定位器,並從被拖動的圖像和板子中的任何單元計算最短距離,從而將圖像放入距離圖像中心最近的單元格中。你的想法很好,謝謝! – photosynthesis

+0

樂意幫忙:D – Tcharni