Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Add Image to TableView Cell

Tags:

I have a UITableView that gets information from a server and publishes the data into a table view. Inside of each cell is the information from the server.

For the purpose of this example, let's say the information we get from the server are numbers: 1, 2, 3, 4.

What I want to do is add an image (programmatically because there are if statements involved, etc) to the left side of the cell, and the text (1, 2, etc) right next to it.

Basically, I want each cell to look like this:

 _____________________________________ | (IMAGE) (TEXT)                      | --CELL 0 --------------------------------------  _____________________________________ | (IMAGE) 2                           | --CELL 1 -------------------------------------- 

Please excuse my crude illustration. :)

like image 485
Baub Avatar asked Aug 24 '11 17:08

Baub


2 Answers

here you go:

cell.imageView.image = [UIImage imageNamed:@"image.png"]; 

Swift:

cell.imageView?.image = UIImage(named: "image.png") 
like image 167
TommyG Avatar answered Oct 09 '22 16:10

TommyG


You can add both the image and the text to the UITableViewCell in your UITableViewController subclass like so:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     static NSString *CellIdentifier = @"Cell";      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];     if (cell == nil) {         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];     }      [[cell imageView] setImage:anImage];     [[cell textLabel] setText:[NSString stringWithFormat:@"%d",[indexPath row]];       return cell; } 

There are a few "built-in" properties to UITableViewCell that you can take advantage of, such as the imageView, textLabel, and detailTextLabel. For more information, check out the Table View Programming Guide.

like image 27
Christopher A Avatar answered Oct 09 '22 16:10

Christopher A