gpt4 book ai didi

ios - 使用自定义类以编程方式创建 UIButton

转载 作者:行者123 更新时间:2023-12-01 16:10:43 25 4
gpt4 key购买 nike

我想以编程方式创建 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;
}
}

//编辑
我所说的自定义类是什么意思:
/image/8r2oz.png

//编辑2(正确答案,因为我无法自己发布答案以更好地指出)

只是在这里指出并更容易找到答案:Greg 的回答是正确的。
您不应该使用默认类创建按钮,而是使用您的自定义类:

代替
UIButton *catBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];


AnswerButton *catBtn = [AnswerButton buttonWithType:UIButtonTypeRoundedRect];

不要忘记导入类(class)!

最佳答案

试试这个...

-(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 的类。 .然后在你的 View Controller 中导入这个类。

之后替换 UIButtonYourCustomButton像..
YourCustomButton *catBtn = [YourCustomButton buttonWithType:UIButtonTypeRoundedRect];

关于ios - 使用自定义类以编程方式创建 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20140727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com