这是我已经解决的问题。源代码
一个枚举类型,表示您想要垂直或水平排列的项目
typedef enum {
ArrangementTypeHorz = 1,
ArrangementTypeVert = 2
}ArrangementType;
声明的数量或行列和排列类型
@interface ATTViewController ()
{
ArrangementType _arrangementType;
NSUInteger _rows;
NSUInteger _columns;
}
@end
方法计算项目索引wrt superView的框架
- (CGRect)frameForItemAtIndex:(NSUInteger)index inSuperView:(UIView *)superView
{
CGFloat blockWidth = floorf(superView.frame.size.width/_columns);
CGFloat blockHeight = floorf(superView.frame.size.height/_rows);
NSUInteger row = 0;
NSUInteger column = 0;
if (_arrangementType == ArrangementTypeHorz) {
row = floorf((CGFloat)index/_columns);
column = index - row*_columns;
}else{
column = floorf((CGFloat)index/_rows);
row = index - column*_rows;
}
CGFloat xOffset = 5.0f;
CGFloat yOffset = 5.0f;
return CGRectMake(blockWidth*column+xOffset,
blockHeight*row+yOffset,
blockWidth-(2*xOffset),
blockHeight-(2*yOffset));
}
将按钮添加到 containerView。添加时设置行、列和排列类型
- (void)addButtonsToContainerView
{
NSUInteger numberOfItems = 5;
_rows = 2;
_columns = 3;
_arrangementType = ArrangementTypeVert;
NSUInteger itemCount = 0;
while (itemCount<numberOfItems)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
CGRect frame = [self frameForItemAtIndex:itemCount inSuperView:self.containerView];
[button setFrame:frame];
NSString *title = [NSString stringWithFormat:@"Button %d",itemCount+1];
[button setTitle:title forState:UIControlStateNormal];
[self.containerView addSubview:button];
itemCount ++;
}
}