iOS 13 之前的设备上的单元格返回意外高度

Unexpected height returned for cell on devices prior to iOS 13

我正在制作一个消息传递应用程序,并根据单元格标签之一的估计框架确定消息单元格的高度。出于某种原因,在 运行 和 iOS 13 之前的 OS 上,返回的高度比需要的要大得多。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let message = messageArr[indexPath.item].messageBody 
        let size = CGSize(width: collectionView.frame.width - 120, height: 1000)            
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        var estimatedFrame = CGRect()
        var cellLbl: UILabel!
        var personLbl: UILabel!

        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CurrentUserMessageCell", for: indexPath) as? CurrentUserMessageCell {
            cellLbl = cell.messageLbl
            personLbl = cell.personLbl
            cell.translatesAutoresizingMaskIntoConstraints = false
        }

        if let font = cellLbl.font {
            estimatedFrame = NSString(string: message).boundingRect(with: size, options: options, attributes: [NSAttributedString.Key.font: font], context: nil)
        }

        let height = estimatedFrame.height + personLbl.frame.height + 16
        return CGSize(width: collectionView.frame.width, height: height)
}

这在所有设备上都很有效,在我更改标签的约束之前,它并不总是占用大部分可用宽度,即使是短消息也是如此。这就是 collectionView.frame.width - 120 的来源(宽度 - 插图,leading/trailing space)。

我已将问题缩小到标签的估计宽度(在 size 属性 中确定)- 但为什么不准确的值不会影响 iOS 13.1 作为高达 12.2?我怎样才能更准确地确定这个值?我已经尝试通过标签的插图和 leading/trailing space 来偏移宽度,但是单元格高度总是太短(字符在 iOS 13.1 之前被截断,而 13.1 只是丢失一点填充)。

这是在 iOS 13.1 上使用上面的代码:



和 12.2:

你的代码有问题:

  • cellForItemAt 之外调用 dequeueReusableCell 是不正确的。
  • 内部 sizeForItemAt 单元格仍未创建,所以不要尝试访问它。

...但为什么不准确的值不会影响 iOS 13.1 和 12.2?

有很多因素,也许只是随机的。可能是因为您正在 sizeForItem 内创建单元格,或者您的估计大小计算逻辑在某些情况下不正确。尝试删除dequeueReusableCell并使用下面中的函数进行计算。


您可以将此扩展程序添加到您的 String 以计算您单元格的 宽度 高度

extension String {

    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)

        return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)

        return ceil(boundingBox.width)
    }
}

里面sizeForItemAt(使用示例)

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let message = messageArr[indexPath.item].messageBody

    // if you want the cell to take the entire width of the collectionView
    // then you can use this width as constrained width
    let estimatedCellWidth = collectionView.frame.width

    // If you want your label inside `cell` have a margin from each side
    // you can add some value to `estimatedHeight` and make it bigger
    // like: estimatedHeight + *some value*, to make final height of cell bigger
    let estimatedHeight = message.height(withConstrainedWidth: estimatedCellWidth, font: /*your current font*/)

    // Some additional logic of calculation if needed ...

    return CGSize(width: estimatedCellWidth, height: estimatedHeight)
}

希望以上内容对您有所帮助!

我建议使用自动布局而不是手动计算单元格高度。

这里有一个很好的教程(不是我的):https://medium.com/@andrea.toso/uicollectionviewcell-dynamic-height-swift-b099b28ddd23

这是一个简单的示例(全部通过代码 - 没有 @IBOutlets)...创建一个新的 UIViewController 并将其自定义 class 分配给 AutoSizeCollectionViewController

//
//  AutoSizeCollectionViewController.swift
//
//  Created by Don Mag on 11/19/19.
//

import UIKit

private let reuseIdentifier = "MyAutoCell"

class MyAutoCell: UICollectionViewCell {

    let personLbl: UILabel = {
        let label = UILabel()
        return label
    }()
    let cellLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        return label
    }()

    // used in systemLayoutSizeFitting() for auto-sizing cells
    lazy var width: NSLayoutConstraint = {
        let width = contentView.widthAnchor.constraint(equalToConstant: bounds.size.width)
        width.isActive = true
        return width
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
        self.setupViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func prepareForReuse() {

    }

    private func setupViews() {

        contentView.backgroundColor = .lightGray

        contentView.layer.cornerRadius = 16.0
        contentView.layer.masksToBounds = true

        // we'll be using contentView ... so disable translates...
        contentView.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(personLbl)
        contentView.addSubview(cellLabel)

        [personLbl, cellLabel].forEach {
            [=10=].translatesAutoresizingMaskIntoConstraints = false
            [=10=].backgroundColor = .clear
            [=10=].textColor = .black
            [=10=].font = UIFont.systemFont(ofSize: 17.0, weight: .bold)
        }

        let g = contentView.layoutMarginsGuide

        // top / bottom padding
        let vPadding: CGFloat = 6.0

        // leading / trailing padding
        let hPadding: CGFloat = 8.0

        // vertical space between labels
        let vSpacing: CGFloat = 6.0

        NSLayoutConstraint.activate([

            // constrain personLbl to top, leading, trailing (with vPadding)
            personLbl.topAnchor.constraint(equalTo: g.topAnchor, constant: vPadding),

            // constrain personLbl to leading and trailing (with hPadding)
            personLbl.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: hPadding),
            personLbl.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -hPadding),

            // constrain cellLabel top to personLbl bottom (with spacing)
            cellLabel.topAnchor.constraint(equalTo: personLbl.bottomAnchor, constant: vSpacing),

            // constrain cellLabel to leading and trailing (with hPadding)
            cellLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: hPadding),
            cellLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -hPadding),

            // constrain cellLabel to bottom (with vPadding)
            cellLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -vPadding),

        ])

    }

    // used for auto-sizing collectionView cell
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        width.constant = bounds.size.width
        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }

}

class AutoSizeCollectionViewController: UIViewController {

    // some sample data
    let theData: [[String]] = [
        ["Joe", "Hi"],
        ["Bob", "Hi back!"],
        ["Joe", "This is a message"],
        ["Bob", "This is a longer message. How does it look?"],
        ["Joe", "Oh yeah? Well, I can type a message that's even longer than yours. See what I mean?"],
        ["Bob", "Well good for you."],
    ]

    var theCollectionView: UICollectionView!
    var theFlowLayout: UICollectionViewFlowLayout!

    override func viewDidLoad() {
        super.viewDidLoad()

        // create vertical flow layout with 16-pt line spacing
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = 0.0
        flowLayout.minimumLineSpacing = 16.0

        // this will be modified in viewDidLayoutSubviews()
        // needs to be small enough to fit on initial load
        flowLayout.estimatedItemSize = CGSize(width: 40.0, height: 40.0)

        theFlowLayout = flowLayout

        // create a collection view
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.alwaysBounceVertical = true
        collectionView.backgroundColor = .clear

        collectionView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(collectionView)

        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            // constraints for the collection view
            // for this example, 100-pts from top, 40-pts from bottom, 80-pts on each side
            collectionView.topAnchor.constraint(equalTo: g.topAnchor, constant: 100.0),
            collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -40.0),
            collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 80.0),
            collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -80.0),

        ])

        theCollectionView = collectionView

        // Register cell classes
        theCollectionView.register(MyAutoCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        theCollectionView.dataSource = self
        theCollectionView.delegate = self

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // collection view frame has now been determined by auto-layout
        // so set estimated item width to collection view frame width
        // height is approximate, as it will be auto-determined by the cell content (the labels)
        theFlowLayout.estimatedItemSize = CGSize(width: theCollectionView.frame.width, height: 100.0)
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        // reset estimated item size width to something small
        // to avoid layout issues on size change (such as device rotation)
        // it will be properly set again in viewDidLayoutSubviews()
        theFlowLayout.estimatedItemSize = CGSize(width: 40.0, height: 40.0)
    }

}

// MARK: UICollectionViewDataSource
extension AutoSizeCollectionViewController: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return theData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyAutoCell

        cell.personLbl.text = theData[indexPath.item][0].uppercased()
        cell.cellLabel.text = theData[indexPath.item][1]

        return cell
    }

}

// MARK: UICollectionViewDelegate

extension AutoSizeCollectionViewController: UICollectionViewDelegate {
    // delegate methods here...
}

结果: