Sravan Sravan - 1 year ago 74
iOS Question

Change UIImageView display/dimensions within a tableview cell

I wanted to hide UIImageView within a cell of UITableview for specific cells based on whether image link is available for that cell row or not.

If a image url is not available from backend for a cell, then I wanted to "disable" UIImageview and reclaim its space for the label to expand.
(UILabel is placed at left and UIImageView is placed at right corner.
Hence if there is no image, then I want the label text to expand to right if it has more text.)

I've tried two solutions:
1. Change the width of the UIImageView to 0 by setting width constraint.

let widthConstraint = NSLayoutConstraint(item: cell.articleImageView as UIView,
attribute: NSLayoutAttribute.Width,
relatedBy: .Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 0,
constant: 0)

2. Remove imageview from the cell.


But as I scroll through and back, other cell's images also getting effected and getting hidden. Same for myImageView.hidden = true.

BTW, I use tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) for retrieving the cell. And the tableview and cell are created at storyboard.

Any help how to reclaim the space occupied by the hidden UIImageview within as cell, but not getting effected to other rows while scrolling?

Answer Source

Instead of adding the constraint programmatically, assign the width in Interface Builder and create an outlet to the width constraint in your code. Then, after dequeueing your cell you can change the width constraint's constant property to 0 if you want it hidden, or to whatever you want its expanded width to be.

Edit: Additionally I reset the constraint's constant property back to original size in prepareForReuse() method of the cell as suggested by @MuhammadZohaibEhsan in below comment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download