我正在尝试根据superView的大小制作一个UIButton网格。我所看到的大多数解决方案都是将滚动视图添加到滚动视图中。但是如果我不想要可滚动网格而只是一个普通的网格呢? 。如何根据超级视图的大小来调整按钮的大小?有人试过吗?真的很感激任何帮助。
-(void)createLayout{
int width =30;
int height =30;
int leftMargin =10;
int topMargin =10;
int xTile;
int yTile;
int xSpacing = 50;
int ySpacing = 50;
for (int c=1; c<=5; c++) {
for (int r=1; r<=10; r++) {
NSLog(@"row : %d col : %d",r,c);
yTile = ((c*ySpacing)+topMargin);
xTile = ((r*xSpacing)+leftMargin);
Test *btn = [Test buttonWithType:UIButtonTypeCustom];
btn.row = r;
btn.column =c;
[btn setTitle:[NSString stringWithFormat:@"%d,%d",btn.row,btn.column] forState:UIControlStateNormal ];
[btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
[btn setBackgroundColor:[UIColor redColor]];
[btn setFrame:CGRectMake(xTile, yTile, width, height)];
[self.scrollView addSubview:btn];
xTile=xTile+10;
}
yTile = yTile+10;
}
}
答案 0 :(得分:0)
回答你的问题我写了一个代码。这样的事情会对你有所帮助。我创建了这个project for you here。检查一下。此外,它并不完全正常,我希望你能够完成它并在完美时做出承诺。
- (UIView *) view : (CGSize) viewSize withButtons : (int) numberOfButtons{
CGRect frame = CGRectZero;
frame.size = viewSize;
UIView *view = [[UIView alloc]initWithFrame:frame];//considering View size is after margine
CGSize buttonSize = [self getButton:numberOfButtons sizeFor:viewSize];
for (int i = 1; i <= numberOfButtons; i++) {
UIButton *button = [[UIButton alloc] initWithFrame:[self getButton:buttonSize frameForIndex:i inView:viewSize]];
[button setTitle:[[NSNumber numberWithInt:i] stringValue] forState:UIControlStateNormal];
[button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[button.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[button.layer setBorderWidth:1.0f];
[view addSubview:button];
}
return view;
}
- (CGRect) getButton : (CGSize) buttonSize frameForIndex : (int) buttonIndex inView : (CGSize) containerSize{
int x = buttonIndex % (int)(containerSize.width / buttonSize.width);
x *= buttonSize.width;
int y = buttonIndex % (int)(containerSize.height / buttonSize.height);
y *= buttonSize.height;
CGRect frame = CGRectZero;
frame.origin = CGPointMake(x, y);
frame.size = buttonSize;
return frame;
}
- (CGSize) getButton : (int) numberOfButtons sizeFor : (CGSize) containerSize{
double containerArea = containerSize.width * containerSize.height;
double areaOfOneButton = containerArea / numberOfButtons;
double edgeOfOneButton = sqrt(areaOfOneButton);
edgeOfOneButton = (edgeOfOneButton > containerSize.width) ? containerSize.width : edgeOfOneButton;
return CGSizeMake(edgeOfOneButton, edgeOfOneButton);
}