Reputation: 9660
I am using the default UITableViewCell which comes with UIImageView, titleLabel and also a description Label. I want to have a fixed size for my UIImageView so all the images are of the same size. At present it looks like this:
The row height for the cell is "Automatic" and here are the properties of the UITableView.
How can I make my UIImageView fixed size?
The images are downloaded asynchronously as shown below:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let dish = self.dishes[indexPath.row]
cell.textLabel?.text = dish.title
cell.imageView?.image = UIImage(named: "placeholder")
cell.detailTextLabel?.text = dish.description
cell.imageView?.setImageFor(url: URL(string: dish.imageURL)!) { image in
cell.imageView?.image = image
cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
cell.imageView?.widthAnchor.constraint(equalToConstant: 50)
cell.imageView?.heightAnchor.constraint(equalToConstant: 50)
cell.setNeedsLayout()
}
return cell
}
UIImageView+Additions.swift
func setImageFor(url :URL, completion: @escaping (UIImage) -> ()) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: url)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
completion(image!)
}
}
}
}
Upvotes: 1
Views: 2797
Reputation: 13283
You are trying to change the height anchor
and width anchor
of your UIImageView
inside your completion block handler
. You should not do that, and if you need to, make sure you are updating your layout in the main thread
.
Your UIImageView
's top, bottom, leading, and trailing anchor
might be equal to the superView
, in your case, it's the tableViewCell
and given that your UITableViewCell
s have auto height. These result to unequal size of your UIImageView
.
Since you are using interface builder, try to layout your UIImageView
like so:
As you can see, I have my fixed width and height of my UIImageView
.
Lastly, don't forget to set your UIImageView
's contentMode
and tick clipToBounds
to yes.
Upvotes: 1