我正在使用customcell
实现UICollection
视图。在这里,我需要根据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's
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)
}
}
根据您的要求添加attributes
和height
。