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

时间:2014-10-11 07:18:54

标签: ios

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

我通过插座宣布了按钮

@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'

1 个答案:

答案 0 :(得分:2)

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

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

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");
}

希望这会有所帮助。