1

I am learning how to create a UICollectionView programmatically. I want to create a grid of pictures collected from the user in another part of the app. Will this sample code help me accomplish this? Also, how do I configure the data to emit the image I want? My source code is below.

UICollectionView:

class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    override func viewDidLoad() {
        super.viewDidLoad()
        let imageStore = ImageStore()
    }

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

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 100, height: 100)

        let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        myCollectionView.dataSource = self
        myCollectionView.delegate = self
        myCollectionView.registerClass(RDCellCollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(myCollectionView)
    }

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

    var images: [UIImage] = [

    ]

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! RDCellCollectionViewCell
        myCell.imageView.image = images[indexPath.item]
        myCell.backgroundColor = UIColor.grayColor()
        return myCell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        print("User tapped on item \(indexPath.row)")
    }
}

ImageStore.swift:

class ImageStore: NSObject {

    let cache = NSCache()

    func setImage(image: UIImage, forKey key: String) {
        cache.setObject(image, forKey: key)

        let imageURL = imageURLForKey(key)

        if let data = UIImageJPEGRepresentation(image, 0.5) {
            data.writeToURL(imageURL, atomically: true)
        }
    }
    func imageForKey(key: String) -> UIImage? {
        if let existingImage = cache.objectForKey(key) as? UIImage {
            return existingImage
        }

        let imageURL = imageURLForKey(key)
        guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
            return nil
        }

        cache.setObject(imageFromDisk, forKey: key)
        return imageFromDisk
    }

    func deleteImageForKey(key: String) {
        cache.removeObjectForKey(key)

        let imageURL = imageURLForKey(key)
        do {
            try NSFileManager.defaultManager().removeItemAtURL(imageURL)
        }
        catch let deleteError {
            print("Error removing the image from disk: \(deleteError)")
        }
    }

    func imageURLForKey(key: String) -> NSURL {
        let documentsDirectories =
        NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        let documentDirectory = documentsDirectories.first!

        return documentDirectory.URLByAppendingPathComponent(key)
    }
}

2 Answers 2

0

You're on the right track. You'll need to create a subclass of UICollectionViewCell that contains a UIImageView; this will let you plug the correct UIImage into it in cellForItemAtIndexPath.

This describes how to hook up your custom cell: Create UICollectionViewCell programmatically without nib or storyboard

As for getting the correct image, you'll need to map the index path to your image store somehow, so that an item number corresponds to the correct image key.

Sign up to request clarification or add additional context in comments.

22 Comments

I reviewed the question that you linked. I am new to this, and am still very confused. What am I supposed to put in my subclass? The goal of the application is to create a UICollectionView of pictures that the user uploaded in another part of the app.
The subclass would contain a UIImageView. Your subclass will add the UIImageView as a subview of its content view, and also you'll need to provide a size for the UIImageView. Then, in cellForRowAtIndexPath, you'll just plug the appropriate UIImage into the cell's UIImageView.
This tutorial looks pretty good: randexdev.com/2014/08/uicollectionviewcell
I created the subclass, but I am still unsure how to show the images collected from the user. I added my subclass to the question.
In viewWillAppear, make sure you register RDCellCollectionViewCell (using the registerClass method of the collection view). Then, in cellForItemAtIndexPath, when you set myCell, add "as! RDCellCollectionViewCell" to the end of the dequeue line; this will make sure that myCell is an instance of your subclass. Then you'll be able to set cell.imageView.image equal to the UIImage you want to show up in the cell.
|
0

If the task is to add an image, you should use something like this in cellForItemAtIndexPath:

let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
myCell.backgroundColor = UIColor.blueColor()
let imageView = UIImageView(frame: cell.contentView.frame)
cell.contentView.addSubview(imageView)
imageView.image = //Here you should get right UIImage like ImageStore().imageForKey("YOUR_KEY")
return myCell

Or you can use custom UICollectionViewCell subclass as Joshua Kaden wrote.

1 Comment

I'd check for the presence of the image view before adding it; otherwise you might wind up adding image view on top of image view (since the cells are potentially reused).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.