Reputation: 91
I'm working on an app to gets data from a JSON an then put the results on a Table, but my problem is that i'm trying to set an image for each cell (same image) but after tried several ways i can't get the image right.
Here some of the code i've tried:
1.- In The background
// Add a background view to the table view
let backgroundImage = UIImage(named: "bookshelf1.png")
let imageView = UIImageView(image: backgroundImage)
self.table.backgroundView = imageView
and in the cell:
cell.textLabel?.text = wifiSpot["ssid"] as? String
cell.backgroundColor = UIColor.clear
It shows like an expanded image of the image not the single image for each cell
2.- In the cell
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
let wifiSpot : NSMutableDictionary = self.tableData[indexPath.row] as! NSMutableDictionary
cell.textLabel?.text = wifiSpot["ssid"] as? String
cell.imageView?.image = UIImage(named: "bookshelf1.png")
But this way overlaps the text and also it shows a white column like if the image doesn't covers the whole cell
![Second Try]: https://i.sstatic.net/pHP6x.jpg
3.- Another way
cell.imageView?.image = UIImage(named: "bookshelf1.png")
cell.textLabel?.text = wifiSpot["ssid"] as? String
It shows like this
![Third Try]: https://i.sstatic.net/w22KH.jpg
I also tried to insert a ImageView on the prototype cell but only shows the image for the cell 1 .
Tried to ctrl drag from the Imageview on the prototype cell to a CustomTableViewCell an the create the cell like this :
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
then call the image from the CustomTableViewCell like this:
cell.postedImage.image = UIImage(named: "bookshelf1.png")
but it doesn't let me create the IBOulet .
Because my reputation it doesn`t let me to post more images
Thanks for your help
Upvotes: 0
Views: 1568
Reputation: 91
I figured out how to do it @Callam this is the code that i used and it worked like i wanted:
var imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 100, height: 200))
let image = UIImage(named: "bookshelf1.png")
cell.backgroundColor = UIColor.clear
imageView = UIImageView(image:image)
cell.backgroundView = imageView
// An then the cell content
cell.textLabel?.text = wifiSpot["ssid"] as? String
cell.textLabel?.textColor = UIColor.white
Here is what i wanted to show:
!https://i.sstatic.net/fpTJT.jpg
Thanks for your Help
Upvotes: 1
Reputation: 11539
Try sending the subview (cell.imageView
) to the back of its superview (cell
).
if let imageView = cell.imageView {
cell.sendSubview(toBack: imageView)
}
Upvotes: 0