创建一个全局按钮计数,int totalButton=5;
并使用tableView显示Gridview,下面的代码将帮助您解决您的问题,它是泛化代码,您可以在Gridview中添加5个以上的按钮:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// add tableView on your View or thr xib
tableView.delegate=self;
tableView.dataSource=self;
[self.view addSubView:tableview];
}
#pragma mark
#pragma mark UITableViewDataSource
//@required
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int numberOfRows=totalButton/3;
if(totalButton%3)
numberOfRows++;
return numberOfRows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// You can create custom cell with xib and drag drop 3 buttons on it and handle the logic to show total buttons on tableview
// Here I am adding buttons as subView to cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (cell == nil) {
// No cell to reuse => create a new one
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"] autorelease];
// Initialize cell
int numberOfRows=totalButton/3;
if(totalButton%3)
numberOfRows++;
if(indexPath.row < numberOfRows) {
int x=10;
for(int i=0; i< 3;i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button.titleLabel setText:@"Button"];
button.tag=i+1;
button.frame = CGRectMake(x, 10.0, 40.0, 40.0);
[cell addSubview:button];
x+=70;
}
}
else {
int x=10;
for(int i=0; i< totalButton%3;i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//[button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button.titleLabel setText:@"Button"];
button.tag=i+1;
button.frame = CGRectMake(x, 10.0, 40.0, 40.0);
[cell addSubview:button];
x+=70;
}
}
}
// Customize cell
return cell;
}