我想以编程方式创建3-4个按钮,但是使用自定义类和特定值/密钥对,但我在如何准确地完成此操作方面很困难。 我想要创建的按钮必须有一个名为“AnswerButton”的自定义类。添加UIButton.tag不应该是一个问题,所以我可以准确地告诉你点击了哪个按钮,对吗?
以下是我用来创建按钮的代码:
NSMutableArray *catNames;
catNames = [NSMutableArray arrayWithCapacity:5];
[catNames addObject:@"Boote"];
[catNames addObject:@"Gewässer"];
[catNames addObject:@"Technik"];
[catNames addObject:@"Krims Krams"];
[self dynamiclyCreateButtons:4 :catNames];
- (void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
//编辑 我的意思是自定义类: https://i.stack.imgur.com/8r2oz.png
//编辑2(正确的答案,因为我无法自己发布答案以更好地指出答案)
就在这里指出并更容易找到答案:Greg的回答是正确的。 您不应该使用默认类创建按钮,而应使用自定义类:
替换
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
带
AnswerButton *catBtn = [AnswerButton buttonWithType:UIButtonTypeRoundedRect];
别忘了导入课程!
答案 0 :(得分:2)
试试这个...
-(void)dynamiclyCreateButtons:(int)howMany :(NSMutableArray*)catNames {
float standard_btnHeight = 30.0;
float standard_btnWidth = 200.0;
CGFloat p = 120;
for(int i = 0; i != howMany; i++){
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[catBtn setFrame:CGRectMake(0.0f, 0.0f, standard_btnWidth, standard_btnHeight)];
[catBtn setCenter:CGPointMake(100.0f, p)];
[catBtn setTag:i];
[catBtn setTitle:[catNames objectAtIndex:i] forState:UIControlStateNormal];
[catBtn addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:catBtn];
p=p+40;
catBtn = nil;
}
}
- (IBAction)buttonClicked:(id)sender
{
NSLog(@"Button.Tag = %d",[sender tag]);
}
编辑:如果要使用自定义类,则必须创建一个继承自UIButton
的类。然后在视图控制器中导入此类。
之后将UIButton
替换为YourCustomButton
,如..
YourCustomButton *catBtn = [YourCustomButton buttonWithType:UIButtonTypeRoundedRect];