简体   繁体   中英

Change height of UIImageview dynamically

I have a UIImageview inside a UITableViewCell whose height need to change depending on the scale of image so I did

override func viewDidLoad() {
    ...
    tableView.estimatedRowHeight = 500.0  //arbitrary value
    tableView.rowHeight = UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //change height of UIImageView
    let image_width = homeViewCell.mainImageView.frame.size.width
    let image_height = image_width * CGFloat(viewModel.imageScale)
    homeViewCell.mainImageView.frame.size.height = image_width * CGFloat(viewModel.imageScale)
    //load image
    _ = homeViewCell.mainImageView.af_setImage(withURL: URL(string: serverURL + viewModel.mainImage)!, placeholderImage: UIImage(named : "home_placeholder") ...
}

In storyboard i have set the height constraint of imageview as fixed number and content mode as "Scale to fill"

This is not resizing the UIImageView based on the scale of image.

Since you're using auto-layout constraints you need to update height constraint not image view frame. So connect your height constraint as an IBOutlet heightConstraint in your tableViewCell. And then in table view cellForRowAt you have to set cell.heightConstraint.constant = image_height . And this will give you the desired result.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // don't forget to dequeue your table view cell here
   //change height of UIImageView
   let image_height = image_width * CGFloat(viewModel.imageScale)
   cell.heightConstraint.constant = image_height
   //load image
   _ = homeViewCell.mainImageView.af_setImage(withURL: URL(string: serverURL + viewModel.mainImage)!, placeholderImage: UIImage(named : "home_placeholder") ...
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM