I'm trying to make a recipe search app. I am trying to get results from the API and also an image associated with these results and display them in a table view, using the basic table view cell.
When I download the image, the image frame is set to its instrinsic size, so it'll be the dimensions of the download image. When I set constraints on this image, it's smaller but you can still see the frame is effecting the text placement.
Here's what it looks like before constraints are set: https://imgur.com/srmKJtV
Here's what it looks like after constraints are set: https://imgur.com/DFLviBK
This is my code I'm using to set the cell up:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "recipe", for: indexPath)
cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
cell.imageView?.heightAnchor.constraint(equalToConstant: 100).isActive = true
cell.imageView?.widthAnchor.constraint(equalToConstant: 100).isActive = true
cell.imageView?.image = recipeResults[indexPath.row].image
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = "\(recipeResults[indexPath.row].title)"
return cell
}
Does anyone know how I can keep the image to be 100x100 and have the text in each row lined up nicely?
I also notice I have an issue with dequeue the cell, as when I click on the row or scroll up/down, the image then turns back to it's normal big size without keeping it small. How can I fix this?
Setting the width and height constraints for your UIImage
is not enough.
Try setting it to center vertical within the cell, and add constraint with your label too. I think it's easier for you to set it in storyboard.
Use custom cell instead of basic
cell.
In this way you'll be able to customize what component you want.
Create your own custom cell via .xib
or in Interface Builder
Add horizontal UIStackView
into your cell and constraint it's leading
, trailing
, top
and bottom
.
Add an imageView
and label
to the stackView
. You should give a width
constraint to your imageView
. In your case it is hard-coded 100
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.