2012-02-12 27 views
2

我有一個UIButtons的數組。我想要做的是用另一個按鈕,隨機設置陣列中每個按鈕的位置。訪問陣列中的UIButton對象的位置

所以我初始化數組與UIButtons

buttonArray = [[NSMutableArray alloc] initWithObjects:button1,button2,button3,button4,button5,button6,button7, nil]; 

然後,我有一個隨機化方法來設置每個按鈕的位置。 這是我卡住的部分。我發現了一些關於不得不在數組中轉換對象類型的線程,以便編譯器能夠理解。但我似乎無法使其工作。

- (IBAction)randomizePositions:(id)sender 
{ 
    for (int i = 0; i < [buttonArray count]; ++i) 
    { 
     float xPos = arc4random() % 1000; 
     float yPos = arc4random() % 700; 
     CGRect randomPosition = CGRectMake(xPos, yPos, button1.frame.size.width, button1.frame.size.width); 
     (UIButton *)[buttonArray objectAtIndex:i].frame = randomPosition; 
    } 
} 

這是這部分,我似乎無法得到正確的。現在很明顯,我是一名初學者,所以任何幫助都會受到很大的關注。

(UIButton *)[buttonArray objectAtIndex:i].frame = randomPosition; 
+0

做一個初學者沒什麼問題;關鍵是你已經嘗試過! :)你能解釋一下這個問題到底是什麼嗎?編譯器錯誤?運行時結果不正確? – 2012-02-12 19:30:47

回答

2

您可能想先抓一個指向UIButton的指針,因爲它可能更容易考慮您正在處理的內容。

- (IBAction)randomizePositions:(id)sender 
{ 
    for (int i = 0; i < [buttonArray count]; ++i) 
    { 
     UIButton *currentButton = (UIButton *)[buttonArray objectAtIndex:i]; 
     float xPos = arc4random() % 1000; 
     float yPos = arc4random() % 700; 
     [currentButton setFrame:CGRectMake(xPos, yPos, currentButton.frame.size.width, currentButton.frame.size.height)]; 
    } 
} 

除非,你當然想要一直使用button1大小。

+0

感謝您的幫助!這工作。但我不確定我明白爲什麼。你正在創建一個新的UIbutton對象,你可以在其中指定我的數組中的一個按鈕。要麼....? – 2012-02-12 20:01:09

+0

它不創建一個新的UIButton對象。相反,它是一個顯式指向數組中的對象的指針。沒有分配或調用[UIButton buttonWithType:...]。 – JacobFennell 2012-02-12 20:18:08

+0

FWIW,'[[buttonArray objectAtIndex:i] setFrame:etc ...]'應該也可以。 – 2012-02-12 20:33:42