[英]UIImageView fit to maximum width in self sizing tableview cells
您应该设置前导,尾随,顶部和底部约束。 因此width
将根据屏幕宽度和调整大小height
将根据图像的纵横比被设定,因为您的单元具有动态高度。
首先,您应该知道使用“ UITableViewAutomaticDimension”设置单元格的高度时,单元格中的UIImageView无法正常工作。
如果您设置“高度限制”并进行更改,则其值将起作用。
因此,请在图像视图中设置“前导”,“尾随”,“顶部”,“底部”和“高度”约束
如果下载了图片,请获取图片的大小并进行数学运算,并为其设置“高度限制”。
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "list")
if let iv = cell?.contentView.viewWithTag(1) as? UIImageView
{
// this UIImageView.image(url: URL, placeHolder: UIImage, complete: (UIImage)->()) is my custom function.
// you can use SDWebImage's function
iv.image(url: URL(string: "http://imageurl")!, placeHolder: nil, complete: { (img) in
// calculate imageview's height
let ivHeight = (iv.frame.size.width * img.size.height) / img.size.width
// get height constraint and set the value.
for lc in iv.constraints
{
if lc.firstAttribute == .height
{
// this will change cell's height automatically
lc.constant = ivHeight
break
}
}
})
}
return cell!
}
对不起,我的英语不好。 :(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.