すべてのビューをループしてグリッドに配置する場合は、次のようにします。
// Array of 9 views
NSArray *views = [NSArray arrayWithObjects:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)], nil];
int count = 0;
int maxPerRow = 3;
int row = 0;
float spacing = 100.0;
for(UIView *view in views)
{
// Only added to tell the difference between views, make sure to import QuartzCore or remove the next 3 lines
view.backgroundColor = [UIColor colorWithRed:.5 green:0 blue:0 alpha:1];
view.layer.borderWidth = 1;
view.layer.borderColor = [UIColor whiteColor].CGColor;
// position view
view.frame = CGRectMake(count*spacing, row * spacing, view.frame.size.width, view.frame.size.height);
[self.view addSubview:view];
if(count % maxPerRow == maxPerRow-1)
{
count = 0;
row++;
}
else
{
count++;
}
}
それはあなたに次のようなものを与えるでしょう: