User23145
User23145

Reputation: 17

How to add image to multiple buttons

my application has 50 buttons.i want to add image to button programmatically to all buttons.

i declared buttons through outlet as

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

this is my array

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

this is my logic

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'

Upvotes: 0

Views: 107

Answers (1)

Viper
Viper

Reputation: 1408

In all button arrays you have string type value and setImage method for UIButton type object, not for NSString type. That's why your code is crashing.

Try this code to create multiple buttons and add to 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;
}

And method to be called -

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

Hope this will help.

Upvotes: 2

Related Questions