Has anyone implemented a decoration view for the iOS 6 UICollectionView? It's impossible to find any tutorial on implementing a decoration view on the web. Basically in my app I have multiple sections, and I just wanted to display a decoration view behind each section. This should be simple to implement but I'm having no luck. This is driving me nuts... Thanks.
A collection view manages an ordered set of content, such as the grid of photos in the Photos app, and presents it visually. Collection views are a collaboration between many different objects, including: Cells. A cell provides the visual representation for each piece of your content. Layouts.
Overview. A flow layout is a type of collection view layout. Items in the collection view flow from one row or column (depending on the scrolling direction) to the next, with each row containing as many cells as will fit. Cells can be the same sizes or different sizes.
A compositional layout is composed of one or more sections that break up the layout into distinct visual groupings. Each section is composed of groups of individual items, the smallest unit of data you want to present. A group might lay out its items in a horizontal row, a vertical column, or a custom arrangement.
Here's a collection view layout decoration view tutorial in Swift (this is Swift 3, Xcode 8 seed 6).
Decoration views are not a UICollectionView feature; they essentially belong to the UICollectionViewLayout. No UICollectionView methods (or delegate or data source methods) mention decoration views. The UICollectionView knows nothing about them; it simply does what it is told.
To supply any decoration views, you will need a UICollectionViewLayout subclass; this subclass is free to define its own properties and delegate protocol methods that customize how its decoration views are configured, but that's entirely up to you.
To illustrate, I'll subclass UICollectionViewFlowLayout to impose a title label at the top of the collection view's content rectangle. This is probably a silly use of a decoration view, but it illustrates the basic principles perfectly. For simplicity, I'll start by hard-coding the whole thing, giving the client no ability to customize any aspect of this view.
There are four steps to implementing a decoration view in a layout subclass:
Define a UICollectionReusableView subclass.
Register the UICollectionReusableView subclass with the layout (not the collection view), by calling register(_:forDecorationViewOfKind:)
. The layout's initializer is a good place to do this.
Implement layoutAttributesForDecorationView(ofKind:at:)
to return layout attributes that position the UICollectionReusableView. To construct the layout attributes, call init(forDecorationViewOfKind:with:)
and configure the attributes.
Override layoutAttributesForElements(in:)
so that the result of layoutAttributesForDecorationView(ofKind:at:)
is included in the returned array.
The last step is what causes the decoration view to appear in the collection view. When the collection view calls layoutAttributesForElements(in:)
, it finds that the resulting array includes layout attributes for a decoration view of a specified kind. The collection view knows nothing about decoration views, so it comes back to the layout, asking for an actual instance of this kind of decoration view. You've registered this kind of decoration view to correspond to your UICollectionReusableView subclass, so your UICollectionReusableView subclass is instantiated and that instance is returned, and the collection view positions it in accordance with the layout attributes.
So let's follow the steps. Define the UICollectionReusableView subclass:
class MyTitleView : UICollectionReusableView { weak var lab : UILabel! override init(frame: CGRect) { super.init(frame:frame) let lab = UILabel(frame:self.bounds) self.addSubview(lab) lab.autoresizingMask = [.flexibleWidth, .flexibleHeight] lab.font = UIFont(name: "GillSans-Bold", size: 40) lab.text = "Testing" self.lab = lab } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Now we turn to our UICollectionViewLayout subclass, which I'll call MyFlowLayout. We register MyTitleView in the layout's initializer; I've also defined some private properties that I'll need for the remaining steps:
private let titleKind = "title" private let titleHeight : CGFloat = 50 private var titleRect : CGRect { return CGRect(10,0,200,self.titleHeight) } override init() { super.init() self.register(MyTitleView.self, forDecorationViewOfKind:self.titleKind) }
Implement layoutAttributesForDecorationView(ofKind:at:)
:
override func layoutAttributesForDecorationView( ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if elementKind == self.titleKind { let atts = UICollectionViewLayoutAttributes( forDecorationViewOfKind:self.titleKind, with:indexPath) atts.frame = self.titleRect return atts } return nil }
Override layoutAttributesForElements(in:)
; the index path here is arbitrary (I ignored it in the preceding code):
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var arr = super.layoutAttributesForElements(in: rect)! if let decatts = self.layoutAttributesForDecorationView( ofKind:self.titleKind, at: IndexPath(item: 0, section: 0)) { if rect.intersects(decatts.frame) { arr.append(decatts) } } return arr }
This works! A title label reading ``Testing'' appears at the top of the collection view.
Now I'll show how to make the label customizable. Instead of the title "Testing," we'll allow the client to set a property that determines the title. I'll give my layout subclass a public title
property:
class MyFlowLayout : UICollectionViewFlowLayout { var title = "" // ... }
Whoever uses this layout should set this property. For example, suppose this collection view is displaying the 50 U.S. states:
func setUpFlowLayout(_ flow:UICollectionViewFlowLayout) { flow.headerReferenceSize = CGSize(50,50) flow.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10) (flow as? MyFlowLayout)?.title = "States" // * }
We now come to a curious puzzle. Our layout has a title
property, the value of which needs to be communicated somehow to our MyTitleView instance. But when can that possibly happen? We are not in charge of instantiating MyTitleView; it happens automatically, when the collection view asks for the instance behind the scenes. There is no moment when the MyFlowLayout instance and the MyTitleView instance meet.
The solution is to use the layout attributes as a messenger. MyFlowLayout never meets MyTitleView, but it does create the layout attributes object that gets passed to the collection view to configure MyFlowLayout. So the layout attributes object is like an envelope. By subclassing UICollectionViewLayoutAttributes, we can include in that envelope any information we like — such as a title:
class MyTitleViewLayoutAttributes : UICollectionViewLayoutAttributes { var title = "" }
There's our envelope! Now we rewrite our implementation of layoutAttributesForDecorationView
. When we instantiate the layout attributes object, we instantiate our subclass and set its title
property:
override func layoutAttributesForDecorationView( ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if elementKind == self.titleKind { let atts = MyTitleViewLayoutAttributes( // * forDecorationViewOfKind:self.titleKind, with:indexPath) atts.title = self.title // * atts.frame = self.titleRect return atts } return nil }
Finally, in MyTitleView, we implement the apply(_:)
method. This will be called when the collection view configures the decoration view — with the layout attributes object as its parameter! So we pull out the title
and use it as the text of our label:
class MyTitleView : UICollectionReusableView { weak var lab : UILabel! // ... the rest as before ... override func apply(_ atts: UICollectionViewLayoutAttributes) { if let atts = atts as? MyTitleViewLayoutAttributes { self.lab.text = atts.title } } }
It's easy to see how you might extend the example to make such label features as font and height customizable. Since we are subclassing UICollectionViewFlowLayout, some further modifications might also be needed to make room for the decoration view by pushing down the other elements. Also, technically, we should override isEqual(_:)
in MyTitleView to differentiate between different titles. All of that is left as an exercise for the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With