首页 > 解决方案 > UICollectionView 中的动态宽度单元格

问题描述

在此处输入图像描述

我尝试使用UICollectionView. 但我必须用动态标签长度设置宽度。我尝试消除图片中的空白。我分享一些代码。我用笔尖。

提前致谢。

layoutFCV.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
let filterCV = UICollectionView(frame: self.view.bounds, collectionViewLayout: layoutFCV)

--

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {       
    if collectionView == filterCollectionView {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterSelectionCollectionViewCell", for: indexPath) as! FilterSelectionCollectionViewCell
        return CGSize(width: cell.title.frame.width , height: self.filterCollectionView.frame.height)
    }  else {
        return CGSize(width: 10, height: 10)
    }
}

标签: iosswiftuicollectionview

解决方案


使用此代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = "Title"
    let width = self.estimatedFrame(text: text, font: UIFont.systemFont(ofSize: 14)).width
    return CGSize(width: width, height: 50.0)
}

func estimatedFrame(text: String, font: UIFont) -> CGRect {
    let size = CGSize(width: 200, height: 1000) // temporary size
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    return NSString(string: text).boundingRect(with: size,
                                               options: options,
                                               attributes: [NSFontAttributeName: font],
                                               context: nil)
}

推荐阅读