我有一些按钮(5个UIButtons),并希望将它们放置在我要放置3个按钮的每一行的网格视图中。
我怎么能放置它们,不知道吗?
-(void)createSubMenusforView:(UIView *)selectedView
{
int y=75;
for(int i=0;i<=([arr count]-1)/3;i++)
{
int si=(selectedView.frame.size.width/3-50)/2;
int x=si+si/2;
for(int j=0;j<3;j++)
{
UIButton *btn_item=[[UIButton alloc]initWithFrame:CGRectMake(x,y,50,50)];
btn_item.backgroundColor=[UIColor grayColor];
[selectedView addSubview:btn_item];
[self doAnimateforView:btn_item forFrame:CGRectMake(btn_item.frame.origin.x, btn_item.frame.origin.y, btn_item.frame.size.width, btn_item.frame.size.height) forDelay:0.5];
x=x+75;
}
y=y+60;
}
}
答案 0 :(得分:1)
创建一个全局按钮计数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;
}