I have a tableview
, how can I add image to the left of this cells?
Swift 5 solution
cell.imageView?.image = UIImage.init(named: "yourImageName")
Try this code:--
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];
For my fellow Swift users, here is the code you will need:
let imageName = "un-child-rights.jpg"
let image = UIImage(named: imageName)
cell.imageView!.image = image
Swift 4 solution:
cell.imageView?.image = UIImage(named: "yourImageName")
All good answers from others. Here are two ways you can solve this:
Directly from the code where you will have to programmatically control the dimensions of the imageview
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
cell.imageView!.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
From the story board, where you can use the attribute inspector & size inspector in the utility pane to adjust positioning, add constraints and specify dimensions
In the storyboard, add an imageView object in to the cell's content view with your desired dimensions and add a tag to the view(imageView) in the attribute inspector. Then do the following in your viewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "xyz", for: indexPath)
...
let pictureView = cell.viewWithTag(119) as! UIImageView //let's assume the tag is set to 119
pictureView.image = UIImage(named: "xyz") // if retrieving the image from the assets folder
return cell
}
Standard UITableViewCell already contains UIImageView that appears to the left to all your labels if its image is set. You can access it using imageView property:
cell.imageView.image = someImage;
If for some reason standard behavior does not suit your needs (note that you can customize properties of that standard image view) then you can add your own UIImageView to the cell as Aman suggested in his answer. But in that approach you'll have to manage cell's layout yourself (e.g. make sure that cell labels do not overlap image). And do not add subviews to the cell directly - add them to cell's contentView:
// DO NOT!
[cell addSubview:imv];
// DO:
[cell.contentView addSubview:imv];