How can I show custom image in UITableView accessory view in Objective-C?

71 Views Asked by At

I am doing a project in Objective-C. My problem is now,

Suppose I have a UITableView I want when I select a row it can show image with current position of user and remaining rows no need to show the same image.

I tried with lot of examples but no use.

can anyone help me? please...

2

There are 2 best solutions below

3
Nirav Bhatt On

Upon row selection, you should grab a cell and create your custom accessory view with that cell:

UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
BOOL bSelected = YES; 
[self createAccessoryView:cell :bSelected];

Note however that bSelected bool above should ideally come from your model array, the array that holds your table view objects. Upon row selection, it will simply negate its value, such as:

bSelected = !bSelected;

Your createAccessoryView would look something like this:

- (void) createAccessoryView : (UITableViewCell *) cell :(BOOL)bSelected
{
    UIImage * image = bSelected ? [UIImage imageNamed:@"check"] : [UIImage imageNamed:@"uncheck"];
    cell.accessoryType = UITableViewCellAccessoryNone;

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGRect frame = CGRectMake(0.0, 0.0, 40, 40);
    button.frame = frame;
    [button setBackgroundImage:image forState:UIControlStateNormal];

//Uncomment below line if necessary
//[button addTarget:self action:@selector(accessoryButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];
    cell.accessoryView = button;
}

Off course, substitute your own image names above.

If you need more functionality in table view with some ready-made customisations (search, select, delete), take a look at this ViewController developed by me on github.

3
Vinu Jacob On

First of all place an image view in your cell, and put it as imgView.hidden = YES. When you select the cell, the image view of that cell to be unhide.

//Sample Code

IndexSelected = 99999 // In viewdidload

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

IndexSelected = indexpath.row;

[tbl reloaddata];

}

-(nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

if(IndexSelected == indexpath.row){

cell.imgView.hidden = NO;

}