UITableViewAutomaticDimension,以编程方式添加图像

时间:2017-04-23 21:06:58

标签: ios swift uitableview

我遇到UITableViewAutomaticDimension问题:

在我的tableview中,我有多个以计算高度创建的图像视图:

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中,我设置了:

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

但高度未正确调整(图像被切断) 任何建议都非常感谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您是否尝试过限制imageView的上边缘和下边缘?即。

let constraintTop = NSLayoutConstraint(item: imageView, 
        attribute: NSLayoutAttribute.top, relatedBy: 
        NSLayoutRelation.equal, toItem: cell.contentView, 
        attribute: NSLayoutAttribute.topMargin, multiplier: 1, 
        constant: 0)
let constraintBottom = NSLayoutConstraint(item: imageView, 
        attribute: NSLayoutAttribute.bottom, relatedBy: 
        NSLayoutRelation.equal, toItem: cell.contentView, 
        attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, 
        constant: 0)
cell.contentView.addConstraints([constraintTop, constraintBottom])
相关问题