mankee mankee - 5 months ago 51
iOS Question

Creating Trover Style Gallery iOS Swift

I'm trying to create a gallery within my iOS swift app which resembles in style what Trover does, so basically I want to have an array of images, specify a max amount of images to fit within one row, and then I want to dynamically generate

UIImageViews
with a frame size determined by the code to create the collage effect below. I know this can be done in android using
recyclerView
, however I am not sure what the best approach would be for this in iOS, I know I can use TableView, CollectionView or StackView however I'm not sure what the easiest approach to this would be...the way I used
CollectionViews
in the past is that they had a static size for the
CollectionViewCell
hence I'm not sure how to adapt them to this purpose.

enter image description here

Answer

From speculation on the image given, we can assume that each 4 items, the layout is the same. So we can use a UICollectionView and we may (see Note at the end of the answer) just have to override collectionView:layout:sizeForItemAtIndexPath: with the following code in Objective-C, but the logic is the same in Swift:

CGFloat wholeWidthAvailable = collectionView.frame.size-interspace; //Since we only show 2 item per line, there is only 1 interspace
CGFloat height;

switch (indexPath.row%2)
{
    case 0:
        height = 100;
        break;
    case 1:
        height = 200;
        break;
    default:
        break;
}
CGFloat width;
switch (indexPath.row%4)
{
    case 0:
        width = wholeWidthAvailable*2./5.;
        break;
    case 1:
        width = wholeWidthAvailable*3./5.;
        break;
    case 2:
        width = wholeWidthAvailable*3./5.;
        break;
    case 3:
        width = wholeWidthAvailable*2./5.;
        break;
    default:
        break;
}
return CGSizeMake(width, height);

Note:
The code is not tested (I wrote it here, I don't know if it compile as such).
I explicitly wrote the two switch case, but it clearly can be used in one, since modulo 2 and modulo 4 can be "joined".
I've chosen 2/5 and 3/5 to fit in width (but you can clearly put the proportion that please you).

Comments