我正在尝试使用 cell label
创建 UICollectionView
水平滚动(就像顶部菜单单行)。在这里,我需要实现不同长度的标签内容,因此基于不同长度的单元格标签应该自动调整其宽度。我正在为我的设计使用 Storyboard。
在我的代码下面
extension CameraViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseID, for: indexPath) as! cameraModeCollectionViewCell
cell.cameraMode.text = self.items[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.item)!")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 40, 0, 40)
}
}
最佳答案
实现 UICollectionViewDelegateFlowLayout 的
方法 collectionView(_:layout:sizeForItemAt)
并计算 collectionViewCell
的 width
width
的 text
,您正在使用 label
填充它。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = self.items[indexPath.row]
let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
return CGSize(width: cellWidth, height: collectionView.bounds.height)
}
在上面的代码中,我使用了 self.items[indexPath.row]
作为 text
的来源。 10.0
是添加到单元格的额外 padding
。
如果 items
array
是可选
,unwrap
self.items 的值[indexPath.row]
使用前。
关于ios - Swift UICollectionView 水平滚动单元格标签宽度根据标签内容长度动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56628779/