【问题标题】:UITableViewAutomaticDimension with programmatically added imagesUITableViewAutomaticDimension 以编程方式添加的图像
【发布时间】:2017-04-23 21:06:58
【问题描述】:

我有一个关于 UITableViewAutomaticDimension 的问题:

在我的表格视图中,我有多个使用计算高度以编程方式创建的图像视图:

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

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

【问题讨论】:

  • 您需要添加约束(以编程方式,因为您以编程方式添加UIImageViews)根据UIImageView 的高度定义UITableViewCell 的高度(或任何定义高度UITableViewCell。这是因为 UITableViewAutomaticDimension 使用约束。
  • 我以编程方式添加了约束,但由于某种原因它没有帮助

标签: ios swift uitableview


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您是否尝试过约束 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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多