Swift CollectionViewCell自动高度

时间:2018-02-27 12:54:23

标签: ios swift uicollectionviewcell

我尝试使用标签内容自动调整单元格大小。 我的手机包含两个标签。第一个标签总是一行,另一个可以是多行。 问题是细胞不会调整大小。这是我的代码:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    CollectionViewHeight.constant = CGFloat(60 + 60 * commentaires.count)
    return commentaires.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = commentCollectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! CustomCollectionViewCell
    cell.contentCommentLabel.text = commentaires[indexPath.row]
    cell.nameCommentLabel.text = commentairesNom[indexPath.row]
    cell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // This is Just for example , for the scenario Step-I -> 1
    let yourWidthOfLable = self.view.bounds.size.width
    let font = UIFont(name: "System", size: 14.0)

    var expectedHeight = heightForLable(text: commentaires[indexPath.row], font: font!, width:yourWidthOfLable )

    print("expectedHeight : " + String(describing: expectedHeight))
    return CGSize(width: view.frame.width, height: expectedHeight)
}

func heightForLable(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height
}

2 个答案:

答案 0 :(得分:0)

通常我使用此代码来配置我的CollectionView:

    private func config_collection()
    {
        self.collection_view.delegate = self
        self.collection_view.dataSource = self
        self.collection_view.keyboardDismissMode = .interactive
        self.collection_view.alwaysBounceVertical = true
        self.collection_view.showsVerticalScrollIndicator = true
        self.collection_view.showsHorizontalScrollIndicator = false

        if let layout = self.collection_view.collectionViewLayout as? UICollectionViewFlowLayout
        {
            layout.scrollDirection = .vertical
            layout.minimumLineSpacing = 2
        }
    }

    extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
    {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                            sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 50)
    }
}

编辑1: 要通过估计高度调整单元格大小,请使用以下代码:

func get_size_height_text(texto: String,
                              ui_view: UIView) -> CGFloat
    {
        let l : [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17)]
        let size = CGSize(width: ui_view.frame.width,
                          height: 1000)
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimateFrame = NSString(string: texto).boundingRect(with: size,
                                                                 options: options,
                                                                 attributes: l,
                                                                 context: nil)
        return estimateFrame.height
    }

要使用它,请运行以下代码:

let height = get_size_height_text(texto: label.text ?? "",
                               ui_view: self.view)

使用此高度,您需要使用您的首选项增加值以在单元格中使用它

答案 1 :(得分:0)

您需要根据UILabel的字体系列,字体大小和宽度以编程方式获取UILabel的高度,然后将此高度添加到UILabel的顶部高度。这是你的细胞总高度。