gpt4 book ai didi

ios - 如何将图像添加到多个按钮

转载 作者:行者123 更新时间:2023-11-28 21:56:41 24 4
gpt4 key购买 nike

我的应用程序有 50 个按钮。我想以编程方式将图像添加到所有按钮。

我通过 socket 将按钮声明为

@property (strong, nonatomic) IBOutlet UIButton *radiobtn1;
@property (strong, nonatomic) IBOutlet UIButton *radiobtn2;
@property (strong, nonatomic) IBOutlet UIButton *radiobtn3.
.
.
@property (strong, nonatomic) IBOutlet UIButton *radiobtn50;

这是我的数组

NSMutableArray *allButtons;
allButtons = [[NSMutableArray alloc] init];
allButtons = [NSMutableArray arrayWithObjects:@"radiobtn1", .....,@"radiobtn50",nil];

这是我的逻辑

for (i = 0; i <= 50; i++)
{

[self.allbuttons[i] setImage:[UIImage imageNamed:@"radioButtonDisabled.png"] forState:UIControlStateSelected];
}



but application is crashing with exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString setImage:forState:]: unrecognized selector sent to instance 0x16d4c'

最佳答案

在所有按钮数组中,对于 UIButton 类型对象,您都有字符串类型值和 setImage 方法,对于 NSString 类型则没有。这就是您的代码崩溃的原因。

尝试使用此代码创建多个按钮并添加到 View 中 -

float leftMargin = 20;
float topMargin = 20;

for (int i=0 ; i<9; i++) {

UIButton *BtnObj = [[UIButton alloc]initWithFrame:CGRectMake(leftMargin, topMargin,100,40)];
[BtnObj setBackgroundImage:[UIImage imageNamed:@"imageName.png"] forState:UIControlStateNormal];
[BtnObj setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[BtnObj addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:BtnObj];

topMargin += 50;
}

以及要调用的方法-

-(void)buttonClicked:(UIButton *)sender{
NSLog(@"Button clicked");
}

希望这会有所帮助。

关于ios - 如何将图像添加到多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26312139/

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