繁体   English   中英

UIImageView适合自调整tableview单元中的最大宽度

[英]UIImageView fit to maximum width in self sizing tableview cells

需要设置哪些自动布局约束,以使表视图单元格内的图像扩展到该单元格的宽度边界(如Twitter应用程序中所示)?

我无法完成它,想知道哪些约束和设置是必需的。

在此处输入图片说明

您应该设置前导,尾随,顶部和底部约束。 因此width将根据屏幕宽度和调整大小height将根据图像的纵横比被设定,因为您的单元具有动态高度。

我只关注宽度约束(前导和尾随),但您也可以类似的方式调整顶部和底部的其他约束。

此外,您可能需要更改图像视图以支持此操作,但这取决于您使用的图像。 我选择了“宽高比填充”以确保它使用了整个宽度。 如果图像尺寸不正确,此设置将裁剪图像的顶部和底部。

在此处输入图片说明

注意,在“添加新约束”窗口中,左侧和右侧的框都有一条实线,表示已选中它们。

您可以根据需要调整imageView以提供一些填充,例如在链接的图像中看到的填充。 设置约束的方法仍然相同,只是框中的值会有所不同。

首先,您应该知道使用“ 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.

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