我有一个水平的集合视图。每个单元格都有标签和图像。
我面临的问题是,当标签从服务器呈现数据时,有时文本太大并且与图像重叠,因为每个单元格的宽度是固定的。
如何根据包含的数据更改集合视图单元格的宽度,以使标签不与图像重叠?
CollectionView确实有一个返回单元格大小的委托方法。
请继承UICollectionViewDelegateFlowLayout
并实施以下方法。
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 30, height: 30)
}
您可以计算标签宽度并将其返回到函数。
希望这会有所帮助。
首先使用与文本关联的字体计算标签文本的宽度。
extension String {
func size(with font: UIFont) -> CGSize {
let fontAttribute = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttribute)
return size
}
}
返回计算出的宽度以及collectionView(_, collectionViewLayout:_, sizeForItemAt)
中的collectionView高度
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Note: Margins are spaces around the cell
// model[indexPath.row].text is the text of label to be shown
let newWidth = model[indexPath.row].text.size(with: labelFont!).width + margins + imageView.width
return CGSize(width: newWidth, height: collectionView.bounds.height)
}
注意:
不要忘记确认你的viewController到UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
。