Best Practice
Best Practice

Reputation: 31

How to setup Horizontal UICollectionView with paging, but items per page arrange from left to right & top to bottom

I had complete setup Horizontal UICollectionView with paging, but currently items per page is arranged from top to bottom and left to right, Now I want that items arrange from left to right & top to bottom.

Example:

currently:

      page 1             page 2
 cell 1 | cell 3 || cell 5 | cell 7
 cell 2 | cell 4 || cell 6 | cell 8

my expected:

      page 1             page 2
 cell 1 | cell 2 || cell 5 | cell 6
 cell 3 | cell 4 || cell 7 | cell 8

I had find solutions many days but don't have any result in SWIFT for my case.


This is my screenshot:

Screenshot 1

Screenshot 2


my source code on git: https://github.com/lhvan89/UICollectionview

//
//  ViewController.swift
//  CollectionView
//
//  Created by mac on 6/19/19.
//  Copyright © 2019 lhvan89. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var itemsCollectionView: UICollectionView!
    @IBOutlet weak var pageControl: UIPageControl!

    private let numberOfItemPerpage = 15

    var listItems: [Item] = [
        Item(title: "Behance", image: "behance", badge: 0),
        Item(title: "Deviantart", image: "deviantart", badge: 1),
        Item(title: "Dribbble", image: "dribbble", badge: 2),
        Item(title: "Dropbox", image: "dropbox", badge: 3),
        Item(title: "Facebook", image: "facebook", badge: 4),
        Item(title: "Flickr", image: "flickr", badge: 5),
        Item(title: "Foursquare", image: "foursquare", badge: 6),
        Item(title: "Google-plus", image: "google-plus", badge: 7),
        Item(title: "Instagram", image: "instagram", badge: 8),
        Item(title: "Line", image: "line", badge: 9),
        Item(title: "Linkedin", image: "linkedin", badge: 10),
        Item(title: "Myspace", image: "myspace", badge: 11),
        Item(title: "Path", image: "path", badge: 12),
        Item(title: "Pinterest", image: "pinterest", badge: 13),
        Item(title: "Quora", image: "quora", badge: 14),
        Item(title: "Skype", image: "skype", badge: 15),
        Item(title: "Snapchat", image: "snapchat", badge: 16),
        Item(title: "Soundcloud", image: "soundcloud", badge: 17),
        Item(title: "Spotify", image: "spotify", badge: 18),
        Item(title: "Swarm", image: "swarm", badge: 19),
        Item(title: "Telegram", image: "telegram", badge: 20),
        Item(title: "Tumblr", image: "tumblr", badge: 21),
        Item(title: "Twitter", image: "twitter", badge: 22),
        Item(title: "Viber", image: "viber", badge: 23),
        Item(title: "Vimeo", image: "vimeo", badge: 24),
        Item(title: "Vine", image: "vine", badge: 25),
        Item(title: "Whatsapp", image: "whatsapp", badge: 26),
        Item(title: "Yelp", image: "yelp", badge: 27),
        Item(title: "Youtube", image: "youtube", badge: 28),
    ]

    override func viewDidLoad() {
        super.viewDidLoad()

        itemsCollectionView.dataSource = self
        itemsCollectionView.delegate = self

         pageControl.numberOfPages = listItems.count/numberOfItemPerpage + (listItems.count % numberOfItemPerpage == 0 ? 0 : 1)

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        itemsCollectionView.reloadData()
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return listItems.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCollectionViewCell", for: indexPath) as? itemCollectionViewCell else { return UICollectionViewCell() }
        cell.loadData(item: listItems[indexPath.row])
        return cell
    }
}

extension ViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let x = scrollView.contentOffset.x
        let w = scrollView.bounds.size.width
        let currentPage = Int(ceil(x/w))
        self.pageControl.currentPage = currentPage
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemWidth = collectionView.frame.size.width / 3
        let itemHeight = (collectionView.frame.size.height / 5) - 4
        return CGSize(width: itemWidth, height: itemHeight)
    }

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

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

}

Thanks from any helps!

Upvotes: 3

Views: 697

Answers (1)

Levan Karanadze
Levan Karanadze

Reputation: 461

Create custom collection view cell, which takes array consisting of four models:

| item 1 | item 2 |

| item 3 | item 4 |

Register it for your collection view. Configure it with your data (setup item 1 with the first element of models array, second one with the second element of models array...).

Now your collection have 2 cells and 2 models array in case described by you:

cell 1:

| item 1 | item 2 |

| item 3 | item 4 |

cell 2:

| item 5 | item 6 |

| item 7 | item 8 |

models1: [ data for item1 , data for item2, data for item3, data for item4 ]

models2: [ data for item5 , data for item6, data for item7, data for item8 ]

//////////////////////

Another simpler solution is rearranging datasource:

[data1, data2, data3, data4, data5, data6, data7, data8]

-->

[data1, data3, data2, data4, data5, data7, data6, data8]

Code for rearranging (Works for your custom case with 4 elements in a single page, !not generic!):

import Foundation

func rearranged(_ data: [Int]) -> [Int] {
    var result = data
    var i = 0
    while i + 1 < data.count {
        if (i + 1) % 2 == 0 && (i + 1) % 4 != 0 {
            let tmp = data[i]
            result[i] = result[i + 1]
            result[i + 1] = tmp
            i += 1
        }
        i += 1
    }
    return result
}
var dataFromServer: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
let data = rearranged(dataFromServer)
print(data)

Upvotes: 2

Related Questions