Обрезать последний UICollectionViewCell, если их общая ширина больше ширины UICollectionViewCell

У меня есть сценарий, в котором у меня есть горизонтальная прокрутка, в которой есть несколько X-ячеек. Ширина ячейки по умолчанию составляет 71 пункт.

В зависимости от значения X у меня может быть меньше ячеек, когда их общая ширина меньше ширины представления коллекции, что нормально. Булочка, если их общая ширина (количество ячеек * 71) больше ширины collectionView, покажите количество ячеек Y, которые идеально подходят, и половину следующей, чтобы пользователь знал, что его можно прокручивать по горизонтали.

Вот что у меня сейчас

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if dataSource.count * 71 <= collectionView.bounds.width {
            return CGSize(width: 71, height: collectionView.bounds.height)
        } else {
            // if it's larger just show Y number of cells with the last one visible cut in half, so the user knows it's horizontally scrollable 
        }
    }
}

4 ответа

Решение

Нашел мое решение, спасибо всем за помощь

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    let collectionViewWidth = self.width
    let numberOfCellsToFit = round(collectionViewWidth / cellWidth)
    let spaceBetweenCells = (collectionViewWidth - cellWidth/2) / (numberOfCellsToFit - 1)

    return (spaceBetweenCells - cellWidth)
   }

Вы можете попробовать этот код:

    extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if dataSource.count * 71 <= collectionView.bounds.width {
            return CGSize(width: 71, height: collectionView.bounds.height)
        } else {
            return CGSize(width:(collectionView.bounds.width/4) * 3, height: collectionView.bounds.height)
        }
    }
}

Что-то вроде этого?

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    let targetWidth: CGFloat = 71
    if dataSource.count * targetWidth <= collectionView.bounds.width {
        return CGSize(width: targetWidth, height: collectionView.bounds.height)
    } else {
        let numberOfCellsToFit = Int(collectionView.bounds.width / targetWidth)
        let cellWidth = collectionView.bounds.width / (CGFloat(i) - 0.5)
        return CGSize(width: cellWidth, height: collectionView.bounds.height)
    }
}

Попробуйте обновить ширину CollectionView при снятии очереди с последней ячейки представления коллекции, примерно так:

 func dequeueReusableCell(withReuseIdentifier identifier: String, 
                     for indexPath: IndexPath) -> UICollectionViewCell {
 let cell = ....
 if cell.width < 71 {
  collectionView.width = collectionView.width - 71 +cell.width
  self.layoutIfNeeded()
 }

}
Другие вопросы по тегам