以编程方式添加图像的 UITableViewAutomaticDimension [英] UITableViewAutomaticDimension with programmatically added images

查看:24
本文介绍了以编程方式添加图像的 UITableViewAutomaticDimension的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UITableViewAutomaticDimension 有问题:

I have a problem with UITableViewAutomaticDimension:

在我的 tableview 中,我有多个 imageviews 以编程方式创建,并计算出高度:

In my tableview I have multiple imageviews created programmatically with calculated height:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "managePlayset", for: indexPath) as! ManagePlaysetTableViewCell
    let playset = playsets[indexPath.row]
    cell.playsetName.text = playset.name
    if (playset.musicItems?.count)! > 0 {
        var i = 0

        for musicItem in (playset.musicItems?.array)! {

            let imageView = UIImageView(image: (musicItem as! MusicItem).getFirstPhoto())
            imageView.frame = CGRect(x: cell.contentView.frame.origin.x+CGFloat(i)*(imageWidth+10.0), y: cell.contentView.frame.origin.y+40, width: imageWidth, height: imageWidth)
            imageView.contentMode = .scaleAspectFit
            cell.contentView.addSubview(imageView)
            let constraint = NSLayoutConstraint(item: imageView, 
            attribute: NSLayoutAttribute.bottomMargin, relatedBy: 
            NSLayoutRelation.equal, toItem: cell.contentView, 
            attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, 
            constant: 0)
            cell.contentView.addConstraint(constraint)

            i = i + 1
        }
    }

    cell.editButton.tag = indexPath.row
    return cell
}

在 viewDidLoad 中我设置:

In viewDidLoad I set:

let width = view.frame.width
    imageWidth = width / CGFloat(maxItemsOnPage) - 10.0
    tableView.estimatedRowHeight = imageWidth + 20.0
    tableView.rowHeight = UITableViewAutomaticDimension

但是高度没有调整好(图片被截断了)任何建议都非常感谢!

But height is not adjusted properly (images are cut off) Any advice is highly appreciated!

推荐答案

我认为这是因为 UIImageView 以编程方式创建的.然后它不使用自动布局系统.要更改它,您必须添加imageView.translatesAutoresizingMaskIntoConstraints = false 在您的循环中.

I think it's because UIImageView created programmatically. Then it don't use autolayout system. To change it, you have to add imageView.translatesAutoresizingMaskIntoConstraints = false in your loop.

这篇关于以编程方式添加图像的 UITableViewAutomaticDimension的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆