【问题标题】:Change height of UIImageview dynamically动态改变 UIImageview 的高度
【发布时间】:2018-11-07 10:59:14
【问题描述】:

我在 UITableViewCell 中有一个 UIImageview,它的高度需要根据图像的比例而改变,所以我这样做了

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") ...
}

在情节提要中,我将 imageview 的高度约束设置为固定数字,并将内容模式设置为“缩放填充”

这不是根据图像的比例调整 UIImageView 的大小。

【问题讨论】:

  • 如果您使用自动布局约束,您不应该尝试更新图像视图的frame。获取对高度约束的引用并改用heightConstraint.constant = image_height。

标签: ios swift uiimageview


【解决方案1】:

由于您使用的是自动布局约束,因此您需要更新高度约束而不是图像视图框架。因此,将您的高度约束连接为 tableViewCell 中的IBOutletheightConstraint。然后在表格视图cellForRowAt 中,您必须设置cell.heightConstraint.constant = image_height。这会给你想要的结果。

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") ...
}

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 2010-11-02
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多