2017-04-23 92 views
2

我有UITableViewAutomaticDimension一个问题:UITableViewAutomaticDimension以编程方式添加图像

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

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 

但高度调整不当(图像被切断) 任何意见是高度赞赏!

+0

您需要添加约束(编程,因为您要添加的'UIImageView's编程),定义了'UITableViewCell'的基于'UIImageView'的高度,高度(或任何确定的高度'UITableViewCell'。这是因为'UITableViewAutomaticDimension'与约束一起工作。 –

+0

我以编程方式添加了约束,但由于某种原因它没有帮助 –

回答

1

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

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])