GoldenBanana GoldenBanana - 3 months ago 58
iOS Question

How to create CollectionView cells one after another in Swift?

This question has already been answered in Objective-C but I couldn't understand the solution because I don't know Objective-C.

I am in the process of making a demo Wallpaper Browser app and require it to display thumbnails in a collection view for the app's launch screen.
I managed to get the job done however these images are loaded collectively which would take a long time for (say) 40 images.

How do I set up my view controller such that the thumbnail images are loaded one by one into the collection view rather than collectively?

The following are the Swift files.

ViewController.Swift

class ViewController: UIViewController , UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!


let imageFetcher = ImageFetcher()
var initialItem = 5

override func viewDidLoad() {
super.viewDidLoad()
//imageFetcher.setImageURL()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return initialItem
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.redColor()
// cell.imageView.image = imageFetcher.ImageArray[indexPath.row]
return cell
}


}

Answer

I wrote some template code for you. Hope this will be helpful.

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!

    var colors = [UIColor]()

    var timer = NSTimer()

    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.colors.append(UIColor.randomColor())

        self.timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: #selector(addCellToCollectionView), userInfo: nil, repeats: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)

        self.timer.invalidate()

    }


    //MARK: - CollectionView Delegate -
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return self.colors.count
    }

    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        UIView.animateWithDuration(0.6, animations: {

            cell.alpha = 1

        })
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
        cell.alpha = 0
        cell.layer.cornerRadius = 12
        cell.backgroundColor = self.colors[indexPath.row]

        return cell
    }


    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let width = (collectionView.frame.size.width-20)/3
        let height = width
        let cellSize = CGSize(width: width, height: height)

        return cellSize
    }



    //MARK: - Timer Selector -
    func addCellToCollectionView(){

        self.counter += 1

        if counter < 30{

            self.colors.append(UIColor.randomColor())
            self.collectionView.reloadSections(NSIndexSet(index: 0))

        }else{

            self.timer.invalidate()
        }

    }

}



//MARK: - Extensions -

extension CGFloat{

    static func random() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }

}

extension UIColor{

    static func randomColor() -> UIColor {
        // If you wanted a random alpha, just create another
        // random number for that too.
        return UIColor(red:   .random(),
                       green: .random(),
                       blue:  .random(),
                       alpha: 1.0)
    }

}

Don't forget to set reusable cell identifier in your .storyboard or .xib file

UPDATE 3 Aug 15:27 (suggestions for GoldenBanana's answer)

var counter = 0

func addCells(timer : NSTimer){

    if(counter == imageFetcher.ImageArray.count){
        timer.invalidate()
        return
    }

    counter = counter + 1

    let indexPath = NSIndexPath(forItem: counter-1 , inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
}



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print("numberOfItemsInSection method just ran")                                                    //timeline indicator
    return counter

}
Comments