如果你想遍历所有视图并将它们放置在一个网格中,你可以这样:
// 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++;
}
}
这会给你这样的东西: