简体   繁体   中英

Dynamically change UITableViewCell's accessory view image

I have a CustomTableView Cell and it has an accessory view. How can I change the accessory view's image dynamically?

Use your custom button for accessoryview like..

// stick the pencil icon on the accessory view

UIButton* pencil = [UIButton buttonWithType:UIButtonTypeCustom];
[pencil setImage:[UIImage imageNamed:@"icon-pencil.gif"] forState:UIControlStateNormal];
pencil.frame = CGRectMake(0, 0, 15, 15);
pencil.userInteractionEnabled = YES;
[pencil addTarget:self action:@selector(didTapEditButton:)      forControlEvents:UIControlEventTouchDown];
cell.accessoryView = pencil; 

不要使用accessoryView,只需放置另一个imageView并相应更改

In the init method of the custom cell, you can do something like (assuming ARC btw):

UIImage *customBtnImg = [UIImage imageNamed:@"custom_btn"];
UIButton *customBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, customBtnImg.size.width, customBtnImg.size.height)];
customBtn.backgroundColor = [UIColor clearColor];
[customBtn setBackgroundImage:customBtnImg forState:UIControlStateNormal];
self.accessoryView = customBtn;

modifications to the cell except textColor and detailTextColor of cell should be done in the willDisplayCell: method and not the cellForRowAtIndexPath method , the solution for your question is as follows --

 -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cellforIndexPath:(NSIndexPath *)indexPath
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageName:@"image.png" forControlState:UIControlStateNormal];
    btn.frame = CGRectMake(0,0,28,28) ;

    cell.accessoryView = btn ;

}

this code will definitely work !!

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