如何以编程方式生成按钮?
问题描述:
你好我困在一个奇怪的情况。我想用循环在视图上生成按钮。 假设我想生成3个按钮。我在我的主视图中添加了一个uiview btnframe。现在我想在该视图中使用该视图的cordinates添加按钮。我要计算btnframe的 范围。如何以编程方式生成按钮?
答
那么你想要你的按钮是多大?如果将它们添加到视图中,它们将继承这些坐标,因此如果您执行0,0,它将位于您将其添加到的视图的左上角。
for(int x=0;x<3;x++){
CGRect rect = CGRectMake(0,20 * x,100,20);
UIButton *button = [[UIButton alloc] initWithFrame:rect];
[btnframe addSubview:button];
.....
}
基本知识,这会给你三个按钮。
如果你想要一个像这样的网格可以工作。
for(int x=0;x<5;x++){
for(int y=0;y<5;y++){
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x * 100, y * 20, 100, 20)];
[button setText:[NSString stringWithFormat:@"%d,%d",x,y]];
[button addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventTouchUpInside];
[mainView addSubview:button];
}
}
这给你25个按钮,每行5个。
我想生成一个网格视图,每个按钮导致一个新的视图 – 2009-06-19 14:52:46