Best way to implement "iOS Photos style" tiled image gallery

Jiho Kang picture Jiho Kang · Nov 18, 2011 · Viewed 8.9k times · Source

I have an app that basically can be used to download, upload, and manage photos from various web services.

I want the image list view to look like the iOS Photos app but not quite sure what the best way to do that is.

I was thinking I could use NSMutableArray and subclass UIScrollView to create that functionality from scratch but I'd really like to use NSFetchedResultsController because some of the data related to the images are dynamically/asynchronously updated/inserted/deleted in Core Data.

Right now I've setup something pretty hacky.
I created an separate Core Data entity to hold relationships to 4 photos in each managed object and I made UITableView loop through them. Then cellforrow delegate would loop through the 4 photos in each table cell. This approach sucks because it's hard to delete and insert photos dynamically and I have to reconstruct relationships and reload the table each time an update is made.

I've looked at some other libraries that do this but I really want to understand what the most simple and efficient way to do this is.

Answer

Marcus S. Zarra picture Marcus S. Zarra · Nov 18, 2011

If you are referring to the tile view, you can duplicate that using a UITableView or a UIScrollView. If you want it to side scroll then a UIScrollView is the starting point.

If you want it to scroll vertically (which I recommend on iPhone) then use a UITableView with a custom UITableViewCell.

As for the Core Data side, you are probably coming at this incorrect, you are trying to store UI state information (how many photos are in a cell) in core data. Core Data should not care about how many images are in a cell.

UITableViewCell

To use a UITableView you would create an array that contains all of your images. You can then determine how many rows you need by dividing that array by the number of images per row.

From there you should subclass UITableViewCell and pass in the 4 images for that cell to draw. Then it is a simple matter of adding 4 UIImageView instances to the custom cell and setting the images.

UIScrollView

For a scrollview you crate a UIImageView for each image and then add them as subviews of the UIScrollView. You would then set the frame of each UIImageView so that they are displayed in a grid.

If you find you have more images than you can hold in memory at once then you will need to deal with tiling, effectively paying attention to where the user is scrolling and filling in (via moving the offscreen image views) ahead of the edge the user is scrolling towards. This is the same thing you get effectively for free with a UITableView via its queuing of cells.