我正在主菜单上创建一个UICollectionView
,所有单元格在最后一个单元格上看起来都很好,在该位置图像相对于单元格没有居中-它似乎锚定在屏幕的左上角单元格(虽然不确定)。
这是包含问题的图像。
我真的不知道从哪里开始,因为所有单元格都使用相同的代码和约束。 通过重复使用以前使用过的图片,我检查出它不是图片问题(请参见上面的屏幕截图)
我唯一的想法是最后一个单元格单独位于一行中,而其他行每行有两个单元格。
extension MainMenuViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mainMenuOptions.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainMenuCell", for: indexPath) as! MainMenuCollectionViewCell
let imageView = cell.mainMenuImage!
let label = cell.mainMenuLabel!
imageView.image = mainMenuImages[indexPath.item]
imageView.frame.size.height = cell.frame.size.width - 5
imageView.frame.size.width = cell.frame.size.width - 10
cell.mainMenuLabel.text = mainMenuOptions[indexPath.item]
let labelText = cell.mainMenuLabel!
label.frame.size.height = Utils.heightForView(text: labelText.text!, font: labelText.font!, width: cell.frame.width)
label.frame.size.width = cell.frame.size.width
label.center.x = cell.frame.size.width / 2
label.center.y = cell.mainMenuImage.frame.size.height + (cell.frame.size.height - cell.mainMenuImage.frame.size.height) / 2
cell.layer.borderColor = UIColor.darkGray.cgColor
cell.layer.borderWidth = CGFloat(0.5)
cell.layer.cornerRadius = CGFloat(10)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainMenuCell", for: indexPath) as! MainMenuCollectionViewCell
let padding: CGFloat = 40
let cellWidth = (collectionView.frame.size.width - padding) / 2
let labelText = mainMenuOptions[indexPath.item]
let cellHeight = cellWidth + Utils.heightForView(text: labelText, font: cell.mainMenuLabel.font!, width: cell.frame.width) + 70
return CGSize(width: cellWidth, height: cellHeight)
}
}
Utils.heightForView()
只是一个函数,用于计算标签适合所有文本所需的大小。如果您需要查看它,我会很乐意添加它。
非常感谢!我希望这是所需的适当数量的代码,但如果不告诉我,我会添加更多。
编辑:单元格类
class MainMenuCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var mainMenuLabel: UILabel!
@IBOutlet weak var mainMenuImage: UIImageView!
}
答案 0 :(得分:0)
当您将cellForItem
中的一个单元出队时,它在那个时候不一定具有最终的大小,但是您依靠的是正确的代码才能正常工作。
您应该使用自动布局约束或单元内部的堆栈视图为您提供正确的布局,而无需在出队时进行任何工作。
您似乎还试图为单元格提供可变的高度,这在流布局中看起来会很混乱,尽管它似乎并没有对屏幕快照中的单元格产生任何影响, d期望获得不同的身高。使sizeForItem
中的单元出队也可能会带来一些意想不到的副作用,因为这将使重用池混乱。