Dynamic UIImageView Size Within UITableView

前端 未结 6 1364
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 13:46

I want to implement a TableView with a Custom TableViewCell showing an image.

To make this simple, I simply put a UIImageView inside a tableviewcell using autolayout

6条回答
  •  天命终不由人
    2020-12-04 14:27

    In the storyboard add trailing, leading, bottom and top constraints to your UIImageView. After you load your image all you need to do is add an aspect constraint to your UIImageView. Your images cell would look something like this:

    class ImageTableViewCell: UITableViewCell {
    
        @IBOutlet weak var customImageView: UIImageView!
    
        internal var aspectConstraint : NSLayoutConstraint? {
            didSet {
                if oldValue != nil {
                    customImageView.removeConstraint(oldValue!)
                }
                if aspectConstraint != nil {
                    customImageView.addConstraint(aspectConstraint!)
                }
            }
        }
    
        override func prepareForReuse() {
            super.prepareForReuse()
            aspectConstraint = nil
        }
    
        func setCustomImage(image : UIImage) {
    
            let aspect = image.size.width / image.size.height
    
            let constraint = NSLayoutConstraint(item: customImageView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: customImageView, attribute: NSLayoutAttribute.height, multiplier: aspect, constant: 0.0)
            constraint.priority = 999
    
            aspectConstraint = constraint
    
            customImageView.image = image
        }
    }
    

    You can check working example here DynamicTableWithImages

提交回复
热议问题