如何确定collectionviewcell的大小(xib)

How to determine the size of collectionviewcell (xib)

一旦数据动态生成,是否有办法从“sizeforitemat”函数或 viewcontroller 的任何其他函数中测量 xib 中定义的单元格的宽度和高度?集合视图的默认布局使其非常简陋,如 output 中所述。主要布局应该最多有两列,其余的空白空间应该在一行内的单元格之间划分。所以我想遍历所有项目,一旦它被数据填充以确定单元格之间的最大大小以根据其大小生成布局。非常感谢您的回复。

viewcontroller.swift

    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegate, 
    UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    @IBOutlet weak var collectionView: UICollectionView!
    let myCell: String = "CollectionViewCell"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.collectionView.register(UINib(nibName:myCell, bundle: nil), forCellWithReuseIdentifier: myCell)
        
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        150
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: myCell, for: indexPath) as! CollectionViewCell
        cell.lbl1.text = "\(indexPath.row)"
        cell.lbl2.text = "\(String(describing: cell.lbl2.text))\(indexPath.row)"
        print ("***", indexPath.item, cell.bounds.size, collectionView.frame.size)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        // TODO: measure width and heigth of each cell to find number of columns
        
        return collectionView.frame.size
    }
}

collectionviewcell.swift


    import UIKit

    class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var lbl1: UILabel!
    @IBOutlet weak var lbl2: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

}

viewcontroller's code

xib file's code

collection view cell

output

要找到“最宽”的单元格,您可以:

  • 创建您的单元实例
  • 遍历您的数据,设置标签值
  • 获取宽度
  • 跟踪最大宽度

像这样:

    let theData: [String] = [
        "Short",
        "Longer",
        "A bit longer",
        "ABC",
        "This is the longest one",
        "Another medium",
        "Last one"
    ]
    
    
    let nib: UINib = UINib(nibName: "CollectionViewCell", bundle: nil)
    let c = nib.instantiate(withOwner: nil, options: nil).first as! CollectionViewCell

    var sz: CGSize = .zero
    var maxW: CGFloat = 0
    
    for i in 0..<theData.count {
    
        c.lbl1.text = "\(i)"
        c.lbl2.text = theData[i]
        
        sz = c.systemLayoutSizeFitting(CGSize(width: .greatestFiniteMagnitude, height: 60.0),
                                       withHorizontalFittingPriority: .defaultLow,
                                       verticalFittingPriority: .required)

        maxW = max(maxW, sz.width)

        print("Row: \(i)", sz)
        
    }
    
    print("Max Width:", maxW)
    

可以在调试输出中给出:

Row: 0 (50.0, 60.0)
Row: 1 (61.5, 60.0)
Row: 2 (95.5, 60.0)
Row: 3 (42.0, 60.0)
Row: 4 (179.5, 60.0)
Row: 5 (134.5, 60.0)
Row: 6 (73.5, 60.0)
Max Width: 179.5