简体   繁体   中英

Change Image of UIButton in UITableView Cell Dynamically

I add UIButton in the cell Dynamically and change UIButton image on click of UIBarButtonItem how i can change?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Display"] ; 
    [cell.textLabel setText:[NSString stringWithFormat:@"%@" ,[arrItemList objectAtIndex:indexPath.row]]];

    UIButton *btnCheck = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnCheck.frame = CGRectMake(6.0f, 2.0f, 32.0f, 25.0f);
    [btnCheck setTitle:@"" forState:UIControlStateNormal]; 
    [btnCheck addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:btnCheck]; 

    return cell;
}
//Here IBAction for Bar Button Item
//when ever user click on BarButton then set the image of all btnCheck
-(IBAction)bbtnCheck:(id)sender
{
}

Assuming that your question is how to change the image of a button w/in every cell of your table when a bar button is clicked, I suggest the following:

Within tableView:cellForRowAtIndexPath, add:

btnCheck.tag = MY_BUTTON_TAG_NUMBER;

Then, when the bar button item is clicked, loop through the visible cells and use the button's tag to identify it and update its image.

-(IBAction)bbtnCheck:(id)sender {
 for (UITableViewCell *cell in self.tableView.visibleCells) {
   UIButton *button = [cell viewWithTag:MY_BUTTON_TAG_NUMBER];
   [button setImage:[UIImage imageNamed:SOME_NEW_IMAGE] forState:UIControlStateNormal];
  }
}

In that bbtnCheck you have to get the instance of that tableView (ie particular cell)..Then after you can get buttons added on that particular cell.. Please Check this....

-(IBAction)bbtnCheck:(id)sender
{
     NSIndexPath *indexpath = [NSIndexPath indexPathForRow:YourRow inSection:YourSection]; // you have to set Row and Section according to your requirement
     UITableViewCell *cellNew = [self.tblComments cellForRowAtIndexPath:indexpath];
    for (UIButton *btn in [cellNew.contentView subviews]) 
    {
        if ([btn isKindOfClass:[UIButton class]]) 
        {
            [btn setImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal];
        }
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM