我正在使用 customcell
实现 UICollection
View 。在这里,我需要根据 customcell
标签字符串创建动态宽度和 static
Height
需要设置。在这里,我使用下面的代码 dynamic
width
不知道静态高度。如何实现?
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return (items[indexPath.row] as String).size(withAttributes: nil)
//return CGSize(width: label.frame.width, height: 33.5)
}
}
最佳答案
根据要添加到 label
中的 text
计算 collectionViewCell 的
width
。
假设 items
是 String
的 array
,
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let textWidth = items[indexPath.row].size(withAttributes:[.font: UIFont.systemFont(ofSize: 20.0)]).width + 30.0 //30.0 is the extra padding
let width = min(textWidth, 100.0) //100.0 is the max width
return CGSize(width: width, height: collectionView.bounds.height)
}
}
根据您的要求添加属性
和高度
。
关于ios - 如何使用 Swift 为 UICollectionView 创建动态宽度和静态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922271/