ios - UICollectionView 中的动态宽度单元格

标签 ios swift uicollectionview

enter image description here

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

提前致谢。

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)
    }
}

最佳答案

使用这段代码:

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)
}

关于ios - UICollectionView 中的动态宽度单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53589870/

相关文章:

objective-c - Cocoa 中未调用我的委托(delegate)操作

ios - 在 tableView 和 scrollView 之间连续滚动

ios - 如何在 CollectionView 中添加 SearchBar?

ios - WkWebview 中的自动填充、保存密码、拼写检查、应用程序缓存

ios - UICollectionView 滚动更改导航和选项卡的颜色如何

ios - 在 Interface Builder 中为 Collection View Cell 设置 Reuse Identifier 有什么意义?

iPhone:获取 Google map 的选定缩放级别

ios - Google Places Autocomplete API 过滤器类型 "address"通过 iOS SDK 返回类型为 "route"的地点

ios - 如何从 NSURLSession 中停止任务或部分

ios - 如何在 Swift 中使用 GRDB 创建多对多关联?