Интервал между ячейками UICollectionView для книжной и альбомной ориентации - PullRequest
0 голосов
/ 13 мая 2019

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

Я хочу 2 ячейки в строке для портретного просмотра и 3 ячейки в ряду для ландшафтного просмотра.

Portrait Orientation Landscape Orientation

Мой код следующий:

override func viewDidLoad() {
    super.viewDidLoad()

    if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
        let itemsPerRow: CGFloat = 2
        let padding: CGFloat = 5
        let totalPadding = padding * (itemsPerRow - 1)
        let individualPadding = totalPadding / itemsPerRow
        let width = (collectionView?.frame.width)! / itemsPerRow - individualPadding
        let height = width
        flowLayout.itemSize = CGSize(width: width, height: height)
        flowLayout.minimumInteritemSpacing = padding
        flowLayout.minimumLineSpacing = padding
    }
}

Ответы [ 3 ]

3 голосов
/ 13 мая 2019

Попробуйте:

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.backgroundColor = .white
    collectionView.alwaysBounceVertical = true
    collectionView.contentInsetAdjustmentBehavior = .always
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 5
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    cell.backgroundColor = .blue
    return cell
}


var spacing: CGFloat = 8

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return spacing
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return spacing
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let safeFrame = view.safeAreaLayoutGuide.layoutFrame
    let size = CGSize(width: safeFrame.width, height: safeFrame.height)
    return setCollectionViewItemSize(size: size)

}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.invalidateLayout()
    }
}

func setCollectionViewItemSize(size: CGSize) -> CGSize {
    if UIApplication.shared.statusBarOrientation.isPortrait {
        let width = (size.width - 1 * spacing) / 2
        return CGSize(width: width, height: width)
    } else {
        let width = (size.width - 2 * spacing) / 3
        return CGSize(width: width, height: width)
    }
}

Результат будет таким:

enter image description here

0 голосов
/ 13 мая 2019

Без лишних слов ...

private var numberOfCellsPerRow: Int {
    return (UIApplication.shared.statusBarOrientation == .portrait) ? 2 : 3
}

private let spacing: CGFloat = 20

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 24
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
}

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.backgroundColor = .orange
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return .zero
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return spacing
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return spacing
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let availableWidth = collectionView.frame.width - CGFloat(numberOfCellsPerRow - 1) * spacing
    let cellWidth = availableWidth / CGFloat(numberOfCellsPerRow)
    return .init(width: cellWidth, height: cellWidth)
}

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    collectionView.collectionViewLayout.invalidateLayout()
}
0 голосов
/ 13 мая 2019

Попробуйте это

Подтвердите UICollectionViewDelegateFlowLayout

Например

class yourViewController: UIViewController,UICollectionViewDelegateFlowLayout
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let screeSize = UIScreen.main.bounds
        let numOfCell:Int = 2 //Number of items you want
        let spaceOfCell:CGFloat = (CGFloat((numOfCell + 1)*10)) //Space between Cells

let orientation = UIApplication.sharedApplication().statusBarOrientation
    if(orientation == .LandscapeLeft || orientation == .LandscapeRight)
    {
       return CGSize(width: Int(screeSize.width - (spaceOfCell/2)) / (numOfCell + 1), height: Int(screeSize.width - spaceOfCell) / numOfCell+1)  

    }
    else
    {
       return CGSize(width: Int(screeSize.width - (spaceOfCell)) / numOfCell, height: Int(screeSize.width - spaceOfCell) / numOfCell)

    }

}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10.00
        //Verticle space between line
    }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10.00 //Space Between Items You want
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...