adding images to UItableView

2019-01-11 12:53发布

问题:

Is it possible to add images to a table view? To the left side? And if so, what size should it be?

回答1:

A custom UITableViewCell is not required to simply add an image to the left side of the cell. Simply configure the imageView property of the UITableView cell in your tableView:cellForRowAtIndexPath: delegate method 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.textLabel.text = @"I'm a UITableViewCell!";
   cell.imageView.image = [UIImage imageNamed:@"MyReallyCoolImage.png"];

   return cell;
}

Unless you provide a tableView:heightForRowAtIndexPath: method in your UITableViewDelegate, the default height of a UITableViewCell is 44 points, which is 44 pixels on a non-retina display and 88 pixels on a retina display.



回答2:

Yes, it is possible. You can take help from cocoawithlove and here. These tutorials will give you an idea how to give images to UITableView. Finally, as asked before on SO, UITableViewCell Set Selected Image.



回答3:

Yes it is, you can add them wherever you like in the cell. Finally, they should be however big (or small) that makes sense to your application.



回答4:

Swift 4 Solution of Thomas answer:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let CellIdentifier = "Cell"
    var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: CellIdentifier)
    if cell == nil {
        cell = UITableViewCell(style: .default, reuseIdentifier: CellIdentifier)
    }
    cell?.textLabel?.text = "I'm a UITableViewCell!"
    cell?.imageView?.image = UIImage(named: "MyReallyCoolImage.png")
    return cell ?? UITableViewCell()
}