UICollectionViewFlowLayout vs subclassing UICollectionViewLayout - ios

I know the documented advice is to use UICollectionViewFlowLayout if you are doing anything "like a grid or a line-based breaking layout". However, I am not sure this is true for my case.
I want a grid but do not want a line-breaking layout. Items should be laid out infinitely both horizontally and vertically without ever stacking. Essentially, a giant chessboard that scrolls horizontally or vertically if content goes beyond the frame.
To subclass UICollectionViewFlowLayout I would have to:
Override prepareLayout to stop the layout from wrapping items. This seems like a lot of work.
Override collectionViewContentSize.
Apple says they have done "lots of hard work" in crafting UICollectionViewFlowLayout, so I should leverage it if I can. But if I have to override prepareLayout to turn off line-breaking, I suspect that I am throwing away a large part of their work. Of their work that is left, I probably will not use most of it anyway (for example, minimumLineSpacingForSectionAtIndex).
Because the layout I want is so simple, I suspect that I should subclass UICollectionViewLayout instead, because:
I will have a simpler and cleaner implementation with everything in one layout class instead of spread between a subclass and a delegate.
I don't think it will be that much harder than subclassing UICollectionViewFlowLayout because I have to override prepareLayout in both cases, and I suspect that is where all the hard work will be.
I'll be in a better position to tweak other UICollectionViewLayoutAttributes in custom ways than trying to add another kludge on top of a UICollectionViewFlowLayout subclass.
Is my conclusion correct?

UICollectionViewFlowLayout can't support two directions anyway, it scrolls along one axis only, either horizontally or vertically. So you have to subclass UICollectionViewLayout not UICollectionViewFlowLayout.
Then you have to override prepareForLayout, layoutsAttributesForElementsInRect methods as you said correctly..

The layout you describe (items arranged in an indefinitely long horizontal line and sections arranged in an indefinitely long vertical line) resembles the "featured" section of the App Store :)
I have been meaning to use a similar concept in some of my apps too, and I think the trick here is that it's not handled by a single UICollectionView. It appears that what you are looking for can be achieved by using a UITableView as a base, and have each section of your content take up a single cell in the table. That is, each UITableViewCell would contain a UICollectionView with horizontal scrolling.
The key limitation of UICollectionView that is sometimes not trivial to understand is that it is, after all, a single scrollView. You can override some functionality to enable scrolling in both directions, but if you want some content to scroll one way, and some content to scroll another way, you would have to create nested scrollViews.

Related

Make UICollectionViewFlowLayout not centering cells on the same line

According to Apple Documents:
If you want to specify different sizes for your cells, you must implement the collectionView:layout:sizeForItemAtIndexPath: method on the collection view delegate. You can use the provided index path information to return the size of the corresponding item. During layout, the flow layout object centers items vertically on the same line, as shown in Figure 3-2. The overall height or width of the line is then determined by the largest item in that dimension.
https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/UsingtheFlowLayout/UsingtheFlowLayout.html#//apple_ref/doc/uid/TP40012334-CH3-SW1
Now I have a collection view with 2 columns and cells varying in height. The problem is that the smaller cell is centered with the taller cell on its left/right, but not float up with the cell under it floats up too.
How can I make that happen?
What I have:
What I want:
It seems like that I should subclass UICollectionViewFlowLayout, but how should I accomplish this?
The type of collection view layout you desire is called "waterfall layout". The implementation is a little bit tricky, since you need to override the basic behaviour of UICollectionViewFlowLayout.
I suggest you to take a look at this tutorial by Ray Wenderlich for building a waterfall layout from the ground, or - if you desire an already packed library - using a library on GitHub, like CHTCollectionViewWaterfallLayout, WaterfallCollectionView or CollectionViewWaterfallLayout
What you want to achieve is called "staggered layout". It was introduced by Pinterest in their iOS app.
You will need custom collection view layout, this tutorial will explain how. Alternatively, you can use one of the existing solutions, for example CHTCollectionViewWaterfallLayout.

How do I layout a UITableViewCell using only frames (no Auto Layout)?

This may sound like a silly question, but most of my experience with iOS development has revolved around Auto Layout being prominent, and I'm curious now (for performance purposes) how I'd go about laying out a cell without Auto Layout and using only frames (and perhaps auto-resizing masks). Turns out this is very hard to Google due to the prominence of Auto Layout.
Essentially am I setting up and adding the subviews in the initWithStyle method of the UITableViewCell subclass?
Positioning wise, am I just relying on the bounds of the contentView, and then if I want one view beside another view, would I basically do newView.frame.origin.x = CGRectGetMaxX(otherView.frame) + spacing?
What happens when I rotate? I know I can watch for rotation in viewWillTransitionToSize, but how do I go about re-positioning the cells? Simply calling tableView.reloadData() would be both expensive and not do much as the cells are laid out in initWithStyle, correct?
I'm targeting iOS 8+.
Any insight would be truly appreciated.
Actually its
newView.frame.origin.x = CGRectGetMaxX(otherView.frame) + spacing + leftMargin;
// you have to include all the spacing, including margins
Tip:
Do not rely on bounds of the contentView by default it is set to maximum width of 320, i suggest you use main screen's frame for that.
AutoLayout is our friend and can save us a lot of time.
how do I go about re-positioning the cells?
If you're planning to do it programmatically, you need to setup the new height and width of the view after the rotation.
Calling tableView.reloadData() to update the views in the cell is not expensive, that's how it works. We don't have a choice but to live with it.
Then it will be better to write the frame calculation portion in viewDidLayoutSubViews.
I'm not entirely certain I understand your question. Please let me know if this makes sense:
Adding Subviews
To add subviews programmatically, it's actually best to do so in the override of layoutSubviews by checking if the contentView has subviews already added and calling a method to add them if needed. This way, you can load the table cell via either a storyboard/nib or using initWithStyle. Alternatively, you can use a shared commonInit method that you call in both initWithCoder and initWithStyle.
Layout of Subviews
To layout your subviews programmatically, you override layoutSubviews (and remember to call super) and set up the frames in that method. This method will be called whenever the view changes size (rotation, initial presentation, etc) and will always include the current bounds of the content view. To calculate your subview frames, you can do so as you've suggested, but you need to define the subview frame and then set the frame for the view:
frameB.origin.x = CGRectGetMaxX(viewA.frame) + spacing;
viewB.frame = frameB;
And keep in mind that this will not correct for the width of frameB. Therefore, you might want to consider using CGRectDivide() instead.
Scrolling performance
That said, the big performance hit when using auto layout in table view cells is not auto layout itself, but the calculations that are done many times on the same set of data to lay it out - all on the main thread. Such as calculating frames for all the text to layout a bunch of labels relative to one another or something that uses drawRect rather than drawing to an image bitmap on a background thread and then loading the image in to a UIImageView once the drawing is complete. Without knowing what data you are displaying it is hard to guess what is causing the performance issues, but you should be sure to use profiling to determine if you are actually improving performance. Additionally, you may need to consider moving some of the number crunching and/or image rendering onto a background thread.
Good luck!

Is subclassing UIView the right way to go about an unknown number of these custom objects?

I have a screen in my app that pulls an unknown sized array from my user object, and must display an object for each item in the array that consists of a UIImageView for my background image, a UISwitch to activate/deactivate that particular item, a label with the name of the item, and a label that corresponds to the name of the item.
These are displayed in a UIScrollView, since there are nearly always going to be more items than will fit on the screen, especially on the iPhone 4.
I had initially quickly thrown together a static screen that consisted of 20 of these objects, but have found that I will often be exceeding that number of items in the array, and need to convert to a dynamic solution.
I have not used subclassing at all yet, and want to be sure that this is the proper solution before I dive into the implementation. Adding one subclass to my scrollView sounds a lot cleaner than adding each of those components individually and figuring out the spacing for various screens.
If this is the proper solution, are there any resources you could point me to to learn about how to properly do this subclassing? I.e., how to add a constructor for the objects where I can add the contents of the labels and state of the switch, and programmatically add constraints. I've only used constraints from the storyboard.
If you do not think that subclassing UIView would be the proper way to do this, what other solution would you suggest? I'm admittedly a novice when it comes to iOS development, so I apologize that this post seeks advice on where to start rather than help fixing a specific part of an implementation.
You should use UITableView or UICollectionView for that, and subclass UITableViewCell or UICollectionViewCell to create your custom view hierarchy.
UITableView and UICollectionView will handle reusing of cells which will help in memory management.
Update:
as you want to use UITableView so to add spacing between cells set number of sections to number of elements and then add header for section and set its height you can do that by implementing UITableViewDelegates visit below links for detail about UITableView and UITableViewDelegates
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/

Why need override layoutSubviews

In the question "When does layoutSubviews get called?" several cases are listed:
The parent view is resized
The device is rotated
Any more?
If there is no requirement to handle, for UITableView, we can create a header view for the section header by creating one customized UIView. The simplest way is to create the UIView by initWithFrame: and then there is no need to relayout any more.
Therefore, in my opinion, we do not need override layoutSubviews etc. But there are some opinions to insist overriding it.
Reasons to not use it:
KISS (keep it simple and stupid )
No requirement for relayout
Relayout has cost when scrolling
My question here is to get more suggestions for this case. Thanks.
You don't usually need to override layoutSubviews. There are basically only two reasons:
Your custom UIView subclass has subviews that you want to rearrange using manual layout
Your custom UIView subclass needs to know when its size changes for some other reasons, like shrinking a font size or doing some manual drawing
Generally speaking, you don't need to override this method. Most layout is done either by the view controller setting the view's frame at appropriate times, or by using auto-layout.

Simple way to stagger cells in UICollectionView

I am working on an iOS app that has a UICollectionView. I would like to make a simple custom layout in which the middle cell on each row is slightly lower than the one on the right and left. I've been looking over tutorials and the apple documentation but most of it is for a much more complicated set up.
Is there is a quick way to stagger the middle cell. Thanks for any input!
Currently the collectionView looks like this...
I simply want the center cells shifted down by 40 pixels or so.
Subclass UICollectionViewFlowLayout and alter the response that the superclass gives so that the cells are positioned where you want them.
Here's an example of a UICollectionViewFlowLayout subclass:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch08p466collectionViewFlowLayout2/ch21p748collectionViewFlowLayout2/MyFlowLayout.swift
It shifts the cells left (so that they are left-justified instead of full-justified across the screen). It is not difficult to see how to adapt this to shift certain cells down.

Resources