【发布时间】:2014-05-31 01:20:36
【问题描述】:
我花了几个小时试图完成我认为很简单的任务。我正在尝试以编程方式在我的 iphone 屏幕上生成 10 个不旋转的方形按钮,而不会重叠。每当我得到我认为正确的代码时,应用程序就会挂起。到目前为止,这是我正在尝试做的事情:
首先我有一个 while 循环,它不断尝试生成按钮,直到有 10 个(因此挂起)。这个循环计算一个随机的宽度和高度来生成按钮。
然后我尝试检查该按钮是否会导致与当前放置在屏幕上的任何按钮重叠(注意:这是为了提高效率而进行的间隔,但已经过测试)。如果按钮可能重叠,我“继续;”,但如果没有,则生成按钮。
生成按钮后,我将不应放置其他按钮的坐标放入其特定的基于轴的数组中,以检查前面的循环。
这是我的代码:
- (void)addNumbers{
int width = [[UIScreen mainScreen] bounds].size.width - 70;
int height = [[UIScreen mainScreen] bounds].size.height - 110;
NSMutableArray* xarray = [[NSMutableArray alloc] init];
NSMutableArray* yarray = [[NSMutableArray alloc] init];
int buttons = 0;
while(buttons < 10) {
int x = 10*floor(10+arc4random_uniform(width)/10);
int y = 10*floor(50+arc4random_uniform(height)/10);
NSLog(@"The coords are: %i, %i",x,y);
if([xarray containsObject:[NSNumber numberWithInt:x]] && [yarray containsObject:[NSNumber numberWithInt:y]]){
NSLog(@"Triggered");
continue;
}
[self generateButton:x :y :buttons];
buttons++;
for(int i = 0; i < 6; i++){
[xarray addObject:[NSNumber numberWithInt:(x+i*10)]];
[yarray addObject:[NSNumber numberWithInt:(y+i*10)]];
[xarray addObject:[NSNumber numberWithInt:(x-i*10)]];
[yarray addObject:[NSNumber numberWithInt:(y-i*10)]];
}
}
}
- (void)generateButton:(int)x :(int)y :(int)num{
UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(x, y, 60, 60);
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn setBackgroundColor:[UIColor whiteColor]];
btn.titleLabel.font = [UIFont fontWithName:@"Avenir" size:40.0f];
[btn setTitle:[NSString stringWithFormat:@"%d",num] forState:UIControlStateNormal];
[self.view addSubview:btn];
[self.squareArray addObject:btn];
}
请帮帮我:'(
我也是 Objective-C 的新手(可能很明显),所以请随时评论我可以改进我的代码或效率的任何方式。
【问题讨论】:
-
这太复杂了。生成随机 x 和 y,制作矩形,然后使用
CGRectIntersectsRect将其与现有矩形进行比较,看看它们是否相交。您可以使用 NSValue 将 CGRect 存储在 NSArray 中。 -
你应该只创建一个包含按钮的数组,而不是维护 xarray 和 yarray。
-
无论如何我可以用按钮来做到这一点,或者得到类似边界框的东西吗?另外,如果我制作了一个数组,无论如何我都必须获得按钮的 x 和 y。
-
随机性是必需的吗?如果没有,这很容易。
-
是的,这是一个要求
标签: ios objective-c