我有一个 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)];
}
}
当然,除非您希望始终使用 Button1 大小。
关于iphone - 访问数组中 UIButton 对象的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9251862/