Reputation: 909
I am using this code for displaying Images in scroll view... In this buttons are created with the help of for loop... and then set image for every buttons... Now i want to select multiple images... I want when i click on particular button, its image replace with "tick image" and when i again pressed on it, replace with original image means show unchecked..
for(int i=0; i<[imageArray count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[buttonImage setImage:[arrayOfImages objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:@selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
}
I tried this code for image changed on state change in (buttonImagePressed) method...
[buttonImage setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateSelected];
but it doesn't work... and it change only image of last button every time instead of particular clicked button.... I also tried to hide the button but it again hide only last button. where i m doing wrong???
there is any another way to change it??? please help me
Upvotes: 0
Views: 244
Reputation: 6152
For this, Take a global flag variable as BOOL Flag = NO;
Set tag for each button also.
In the method
-(IBAction)buttonImagePressed:(UIButton *)sender{
if(flag==NO){
flag=YES;
[sender setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateNormal];
}
else{
flag=NO;
[sender setImage:[arrayOfImages objectAtIndex:sender.tag] forState:UIControlStateNormal];
}
}
Upvotes: 1
Reputation: 3408
Instead of UIControlStateSelected you should use UIControlStateNormal and keep some bool value which shows whether that button is previously selected or not or you can set selected property of button to true or false based on selection say:
-(void) buttonImagePressed:(UIButton*)sender
{
UIButton *button = sender;
if(button.selected) //already selected so now it should be deselected
{
[button setImage:[UIImage imageNamed:@"UnCheckmark.png"] forState:UIControlStateNormal];
button.selected = false;
}
else
{
[button setImage:[UIImage imageNamed:@"Checkmark.png"] forState:UIControlStateNormal];
button.selected = true;
}
}
Upvotes: 4