Центрировать горизонтальный UICollectionView на основе содержимого - PullRequest
0 голосов
/ 04 августа 2020

У меня есть горизонтальный UICollectionView, который отлично работает. Но я хочу центрировать ячейку, когда нет необходимости в прокрутке. т.е.

  1. если вся ячейка может уместиться в пределах ширины просмотра, и пользователю не нужно прокручивать тогда Центрировать ячейку
  2. если вся ячейка не может уместиться в пределах ширины просмотра и пользователю необходимо прокрутить затем Не центрировать ячейку (поведение по умолчанию)

Графический пример:

  1. UICollectionView, который требует прокрутки, затем сохраните поведение по умолчанию

enter image description here

  1. UICollectionView, который не требуется прокрутка

enter image description here

What I have tried so far:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var dataList:[String] = ["icon_rotate", "icon_rotate2", "icon_rotate3", "icon_rotate4", "icon_rotate5", "icon_rotate6"]

 
    override func viewDidLoad() {
       super.viewDidLoad()
       //other stuff
    }

    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
      return (UIDevice.current.userInterfaceIdiom == .pad) ? 20.0 : 10.0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
      return (UIDevice.current.userInterfaceIdiom == .pad) ? 20.0 : 10.0
    }



    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       return CGSize(width: collectionView.frame.size.height * 0.75, height: collectionView.frame.size.height * 0.75)
     }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
      return dataList.count
     }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "editorCell", for: indexPath) as! EditorCell
    
    cell.iconView.image = UIImage(named: dataList[indexPath.row])
    
    
    return cell
   }

}

This results in default behavior of UICollectionView so I searched in SO and found this post: Как центрировать по горизонтали ячейки UICollectionView? , и я добавил этот код:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

  let totalCellWidth = CellWidth * CellCount
  let totalSpacingWidth = CellSpacing * (CellCount - 1)

  let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
  let rightInset = leftInset

  return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}

Этот код работает нормально, когда нужно загрузить несколько ячеек, но я хочу, чтобы он динамически определял, требуется ли центрирование, или позволял поведению по умолчанию оставаться в действии.

Спасибо

1 Ответ

1 голос
/ 04 августа 2020

Предполагая, что ваш текущий код работает, когда вам подходят ячейки - то есть он центрирует «строку ячеек», когда это необходимо - измените эту строку:

let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2

на:

let leftInset = max(0, (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2.0)

Так ваши вставки никогда не будут меньше нуля

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...