Swift中如何根据图片的高度让UITableViewCell Size

How to make UITableViewCell Size according to the height of the image in Swift

我有一个 UITableViewCell,里面有一个 UIImageView。我应该添加什么约束,以便单元格高度根据图像高度动态变化。 ImageView中的图片高度不一,所以我不想固定UIImageView

的高度

有一个委托来定义每一行的高度。我不知道是否有另一种更快的解决方案。

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //get UIImage of the image for this row
        //and return image height
        if let img = UIImage(contentsOfFile: "") {
            return img.size.height
        } else {
            return DEFAULT_HEIGHT
        }
    }

如果您必须从 Internet 下载,您应该为该委托回调定义一个 default_heigth。然后,当下载图像时,您使用下载图像的新高度在关联的索引路径上调用 reloadTable