如何根据iOS中superview的大小制作UIButton网格?
Posted
技术标签:
【中文标题】如何根据iOS中superview的大小制作UIButton网格?【英文标题】:How to make a UIButton grid according to size of superview in iOS? 【发布时间】:2014-09-08 06:44:28 【问题描述】:我正在尝试根据 superView 的大小制作一个 UIButton Grid。我见过的大多数解决方案都是将按钮添加到 scrollView 。但是如果我不想要可滚动的网格而只是一个普通的网格怎么办.如何根据绘制按钮的超级视图的大小调整按钮的大小?。有人尝试过吗?非常感谢任何帮助。
-(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;
【问题讨论】:
将它们放在layoutSubviews
中。
你能详细解释一下吗:-]
【参考方案1】:
为了回答你的问题,我写了一个代码。这样的事情会帮助你。我创建了这个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);
【讨论】:
感谢您提供如此详细的答案。一定会努力解决的:-]以上是关于如何根据iOS中superview的大小制作UIButton网格?的主要内容,如果未能解决你的问题,请参考以下文章
在 iOS 6 中使用 Auto Layout 在 superview 中均匀分布相同大小的 UIView