Different image in each UITableview cell

I want to set a different image for each cell of my table view. I do not know how to do this - please help me.

+3
source share
2 answers

You can create a custom cell with a UIImageView in it, but the easiest way is to create a default image view for the UITableViewCell in your table view delegate -cellForRowAtIndexPath. Something like that:

UITableViewCell *cell = [tableView 
                              dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
    //... other cell initializations here
}

[[cell imageView] setImage:image];

Where image is a UIImage that you created when you download from a URL or from a local application package.

+5
source
  • .

    (.h):

    @interface MyViewController : UITableViewController {
        NSArray *cellIconNames;
        // Other instance variables...
    }
    @property (nonatomic, retain) NSArray *cellIconNames;
    // Other properties & method declarations...
    @end
    

    (.m):

    @implementation MyViewController
    @synthesize cellIconNames;
    // Other implementation code...
    @end
    
  • viewDidLoad cellIconNames , ( , ):

    [self setCellIconNames:[NSArray arrayWithObjects:@"Lake.png", @"Tree.png", @"Water.png", @"Sky.png", @"Cat.png", nil]];
    
  • tableView:cellForRowAtIndexPath: , :

    NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
    

    UIImage ( cellIconName, ) imageView UIImage:

    UIImage *cellIcon = [UIImage imageNamed:cellIconName];
    [[cell imageView] setImage:cellIcon];
    

3 tableView:cellForRowAtIndexPath: :

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

    /* Initialise the cell */

    static NSString *CellIdentifier = @"MyTableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    /* Configure the cell */

    NSString *cellIconName = [[self cellIconNames] objectAtIndex:[indexPath row]];
    UIImage *cellIcon = [UIImage imageNamed:cellIconName];
    [[cell imageView] setImage:cellIcon];

    // Other cell configuration code...

    return cell;
}
+9

Source: https://habr.com/ru/post/1724802/


All Articles