ios - 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)
}
}
解决方案
使用此代码:
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)
}
推荐阅读
- javascript - Laravel Livewire and Cashier double form submit issue
- javascript - 选择选项不显示角度编辑模式期间选择的值
- python - Python如何在executor.map中传递参数对列表
- json - 如何在 Json 响应中删除“数据”数组键
- node.js - 如何使用数千个 Promise 等待多个函数 Firebase Functions
- c++ - 使用不同项目中的自定义类作为 C++ 类的成员 - 错误
- javascript - 数据表和 jquery 不执行选择器按钮单击
- visual-studio-code - VScode中注释代码的括号突出显示
- python - 无法在 PyCharm 中安装任何软件包
- react-native - WKWebview cookie 问题?