我一直在使用自定义UICollectionViewFlowLayout
来调整单元格之间的间隔,以便在collectionView
中获得良好的流动。但是用我当前的代码,我无法弄清楚如何在不“破坏”行数的情况下调整单元格的大小。这使一些单元格认为它们可以容纳一行,但不能容纳。
class UserProfileTagsFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributesForElementsInRect = super.layoutAttributesForElements(in: rect)
var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]()
var leftMargin: CGFloat = 0.0;
for attributes in attributesForElementsInRect! {
if (attributes.frame.origin.x == self.sectionInset.left) {
leftMargin = self.sectionInset.left
} else {
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = leftMargin
attributes.frame = newLeftAlignedFrame
}
leftMargin += attributes.frame.size.width + 8 // Makes the space between cells
newAttributesForElementsInRect.append(attributes)
}
return newAttributesForElementsInRect
}
}
所以我在ViewController
中扩展了
extension myViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let tag = tagsArray[indexPath.row]
let font = UIFont(name: "Raleway", size: 14)!
let size = tag.value.size(withAttributes: [NSAttributedString.Key.font: font])
let dynamicCellWidth = size.width
/*
The "+ 20" gives me the padding inside the cell
*/
return CGSize(width: dynamicCellWidth + 20, height: 35)
}
// Space between rows
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
// Space between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
}
当我尝试这段代码时,我在iPhone X的结果部分中得到了结果。您可以看到标签“ Machine Learning”跳到了新的一行,因为它认为它可以容纳该行以上。如果我删除了sizeForItem
函数中单元格的“填充”,则不会有此问题。但这看起来糟透了。
所以我的问题是:如何在不破坏flowLayout的情况下在单元格上使用填充?
iPhone X:
答案 0 :(得分:2)
也许会对您有所帮助。我认为您应该检查您的项目是否突出了收藏视图右插图。
在layoutAttributesForElements
方法中,请检查以下内容:
let collectionViewWidth = self.collectionView?.frame.width - (self.sectionInset.right + self.sectionInset.left)
if (attributes.frame.origin.x + attributes.frame.size.width > collectionViewWidth) {
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = self.sectionInset.left
attributes.frame = newLeftAlignedFrame
}
更新了我的答案,它对我有用,您可以在屏幕截图上看到它