访问数组中UIButton对象的位置



我有一个UIButtons数组。我想做的是使用另一个按钮,随机设置阵列中每个按钮的位置。

所以我用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;

您可能希望早些时候在数组中获取一个指向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)];
    }
}

当然,除非你想一直使用1号纽扣。

最新更新