Search code examples
iosuitableviewuiimageviewstoryboardnslayoutconstraint

Add NSLayoutConstraint between UIImageView and UITableViewCell


I'm trying to add constraints between two elements inside a UITableViewController and so far, I haven't been able to. The UIImage View in inside the UITableViewController, but outside the UITableView Cell.

I can neither use StoryBoard, nor add constraints programatically because Xcode tells me that I can't add a constraint on an object that is going to be reused.

The reason I'm trying to add a constraint is because the UIImageView is dynamically resized by the size of the image that is downloaded. When the image can't be downloaded for whatever reason, it uses a default image and the whole layout falls apart.

Here's what my tableView looks like:

enter image description here


Solution

  • You may consider to wrap your UIImageView into UITableViewCell and put it as the first cell in the UITableView. Moreover, you can break down the hierarchy of your cells in the table view into 2 sections, so it would ease the tracking of your cells. So the first section would contain only the UIImageView cell and the second section would contain your main cells.

    Whenever you'll get the response from network request which indicates that the image is fetched, you can call tableView.reloadSections(IndexSet(integer: 0), with: .none) and in the delegate method return the correct height

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) {
      if indexPath.section == 0 {
        return imageHeight
      }
    }