Вы не можете использовать 52
напрямую, поскольку в качестве cell width
, так как width
каждого cell
равно dynamic
.
Вам необходимо вычислить leftInsets
и rightInsets
collectionView
на основе actual width
из first
и last
cell
.
Вы можете вычислить width
из first
и last
cell
таким же образомВы использовали метод collectionView(_:layout:sizeForItemAt)
, используя first
и last
element
из items array
, то есть
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//Calculate width of first cell
var firstCellWidth: CGFloat = 52.0
if let textAtFirstIndex = self.items.first {
firstCellWidth = textAtFirstIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
}
//Calculate width of last cell
var lastCellWidth: CGFloat = 52.0
if let textAtLastIndex = self.items.last {
lastCellWidth = textAtLastIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
}
//Calculate leftInset and rightInset
let leftInset: CGFloat = (collectionView.frame.width * 0.5) - (firstCellWidth * 0.5)
let rightInset: CGFloat = (collectionView.frame.width * 0.5) - (lastCellWidth * 0.5)
return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}
Пример:
Дайте мне знать, если у вас все еще есть какие-либо проблемы.