Reprinted from: Ye Isolated City
Uicollectionview Custom Layouts Pintere
Uicollection this thing is pushed out in iOS6, so if your app is still supporting iOS5 or honest with tableview, or you can use ScrollView hand to come out
The best part of it is that custom's layout can play an infinite number of possibilities. For a simple example, there was a very famous Coverflow third-party library Icarousel in the early years (about 13 I used it very frequently), and the effect was very dazzling, But the problem is that it is used ScrollView, although the inside will cache some view to use, to maintain fluency, but there is no CollectionView + layout to smooth. And if it's a program ape that's going to play, Really can write the very cool effect of layout.
First at this address. Download the Raywenderlich start Project.
Run. The effect is like this.
The effect is nothing unusual, is the simplest uicollectionflowlayout effect, put a cell from left to right row, if the right to the screen head, Put it down and run to the next line. Continue from left to right the Cell.collectionview will set the minimum spacing for each cell according to whether you have set minimuminteritemspacing. and minimumlinespacing to set the minimum spacing for one row and one row.
In fact, TableView plainly, can completely customize a layout, through the CollectionView to achieve.
Let's look at the file structure.
Controllers There is nothing to say, is a viewcontroller.
Extensions wrote a uiimage classification, used to decompression, I looked at a bit, in fact, with Uigraphicsgetimagefromcurrentimagecontext regenerated a uiimage.
Models is a photo of the model, including a picture, a picture of the title and message. This model forms the content of our Uicollectionviewcell.
There is also a heightforcomment method that calculates the height of the text content in the label by means of the Boundingrectwithsize method.
Assets is our picture resources and text resources.
Well, now we're going to create a new class that inherits from Uicollectionviewlayout (note, not uicollectionviewflowlayout). Named Pinterestlayout, put it in the group of our layout.
Then select our CollectionView in the storyboard.
Open the attributes Inspector and do the operation.
OK, run straight up.
There's nothing!
Nothing is right, you create a new layout, there is nothing to write, certainly no effect.
Core layout process (processing of kernel layouts)
Let's see how Uicollectionview and Uicollectionviewlayout work together.
When you inherit a layout, there are three ways to override it.
-
Preparelayout (): What does this method do? This is how you calculate the size of each item's position and CollectionView in this method when your layout is about to take effect. Unfold, What is the easiest way to improve the smoothness of tableview? It is very simple, do not calculate the height directly in the Heightforrow proxy method. Instead, calculate the height after the network pulls all the data, put it in the array, and return directly to the proxy method Heightarray [Indexpath.row]. So why calculate each item's position in Preparelayout, the intent is obvious. Just don't let the system calculate each cell's frame each time it scrolls. (How to improve TableView's performance to see Vvbo's demo.)
-
Collectionviewcontentsize (): The meaning of this method is also very simple, is to return CollectionView contentsize. is contentsize instead of size.
-
Layoutattributesforelementsinrect (_:): Returns the properties of a particular area's layout in this method. It's a little bit around, then I'll simply say. eg. there is a collectionview,contentsize is (320, ), size is (320, 400), this time I slipped and slipped and slid to (0, 544, 320, 400). OK, so in this area, how many cells are there, and what are the locations of each cell? Is learned through this method. You don't tell CollectionView how he knows how to put the cell, right.
OK, let's take a look at the idea now.
Look at the picture above, a represents collectionview,b for layout.
A first ask B, my cup (size) is how much, C or d? - -!.
b tell him.
A Q: How much is my contentsize.
b tell him.
A This time the offset has changed, every slide, a will ask, I now this position, there are several cells, each cell location, Transform, what is it?
b tell him.
That's it.
Calculating Layout Attributes (properties of the calculated layout)
OK, let's start our writing Pinterest tour formally.
So the question is, what is the toughest problem we are facing now?
Pay attention to this picture.
Each cell has a fixed width and is variable in length.
This is the core issue of the entire layout.
All the difficulty is how to learn the height of each item.
Just introduced photo This model, I said the decision cell height of only three, 1. Height of 2title height of image 3. The height of the content.
How do I get the height of the picture and the height of the text?
Agent Bai.
Declare a pinterestlayoutdelegate in layout
protocol Pinterestlayoutdelegate { // 1 func collectionview (CollectionView: Uicollectionview, Heightforphotoatindexpath Indexpath:nsindexpath, cgfloat // 2 func collectionview (Collectionview:uicollectionview, CGFloat}
The first is through the agent to get the height of the picture, the second is through the agent to get the height of the text.
Through the agent to get the data we want, next, is to calculate the item frame in the Preparelayout.
Look directly at the code.
Overridefunc preparelayout () {//1. Only calculate once ifCache.isempty {//2. Pre-calculates the X offset for every column and adds a array to increment the currently Max Y Offset for each CO Lumn//width per columnLet columnWidth = contentwidth/cgfloat (NumberOfColumns) var xoffset=[CGFloat] ()//in fact, is Xoffset is two, are fixed. forColumninch 0.. <numberofcolumns {xoffset.append (cgfloat (column)*columnWidth)} var column=0var yoffset= [CGFloat] (Count:numberofcolumns, Repeatedvalue:0) //3. Iterates through the list of items in the first section forIteminch 0.. < collectionview!. Numberofitemsinsection (0) {Let Indexpath= Nsindexpath (Foritem:item, Insection:0) //4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame. //this width is to calculate the length of the comment.Let width = columnwidth-cellpadding*2Let photoheight=Delegate. CollectionView (collectionview!, Heightforphotoatindexpath:indexpath, withwidth:width) let Annotationheight=Delegate. CollectionView (collectionview!, Heightforannotationatindexpath:indexpath, withwidth:width) Let height= cellpadding + photoheight + annotationheight +cellpadding Let frame=CGRect (X:xoffset[column], Y:yoffset[column], width:columnwidth, height:height) let Insetframe=Cgrectinset (frame, cellpadding, cellpadding)//5. Creates an Uicollectionviewlayoutitem with the frame and add it to the cacheLet attributes =pinterestlayoutattributes (forcellwithindexpath:indexpath) attributes.photoheight=photoheight Attributes.frame=insetframe cache.append (attributes)//6. Updates The collection view content heightContentheight =Max (Contentheight, Cgrectgetmaxy (frame)) Yoffset[column]= Yoffset[column] +Height Column= Column >= (NumberOfColumns-1) ?0: ++column}} }
I wrote a little note to make it easy for everyone to watch.
-
The first sentence if Cache.isempty: Determines whether the array that caches the item height is empty and is empty and needs to be computed.
-
Let ColumnWidth = Contentwidth/cgfloat (NumberOfColumns): Calculates the width of each column, the width of each column is fixed, the contentwidth of CollectionView is divided by 2, and the three columns are divided by 3. Contentwidth is the left and right inset in the bounds.width-contentinset of CollectionView.
-
var xoffset = [CGFloat] (): The X coordinate used to store each item, in fact, the X coordinate of all item is only two.
-
var yoffset = [CGFloat] (Count:numberofcolumns, repeatedvalue:0): Initializes the y-coordinate of item for each column, which is an array with two elements.
Y coordinate this thing is a little bit around, first look at a picture.
This collectionview is divided into two columns, in fact? There is no concept of collectionview in the list. Because the permutations are always arranged from left to right.
But now, the second cell's y-axis is actually related to the height of the 0th cell, and the third one is related to the first.
So Yoffset has two values in this array, and when the cell in the first column calculates the height, he goes to yoffset[0] and takes the data, because Yoffset[0] only has the height of the last cell in the first column, so in the same way, when we go to the second column, Will go to yoffset[1] and take the height of the last cell in the second column.
The whole process he used such a sentence to judge.
1 0 : ++column.
Read the logical judgment in the For loop.
OverrideFunc preparelayout () {//1 ifCache.isempty {//2Let ColumnWidth = Contentwidth/cgfloat (numberofcolumns) var xoffset = [CGFloat] () forColumninch 0.. <numberofcolumns {xoffset.append (cgfloat (column)*columnWidth)} var column=0var yoffset= [CGFloat] (Count:numberofcolumns, Repeatedvalue:0)//3 forIteminch 0.. < collectionview!. Numberofitemsinsection (0) {Let Indexpath = Nsindexpath (Foritem:item, Insection:0)//4Let width = columnwidth-cellpadding *2Let photoheight=Delegate. CollectionView (collectionview!, Heightforphotoatindexpath:indexpath, withwidth:width) let Annotationheight=Delegate. CollectionView (collectionview!, Heightforannotationatindexpath:indexpath, withwidth:width) Let height= cellpadding + photoheight + annotationheight + cellpadding Let frame = CGRect (X:xoffset[column], Y:yoffset[colum N], Width:columnwidth, height:height) Let Insetframe = Cgrectinset (frame, cellpadding, cellpadding)//5Let attributes =uicollectionviewlayoutattributes (forcellwithindexpath:indexpath) attributes.frame=insetframe cache.append (attributes)//6Contentheight =Max (Contentheight, Cgrectgetmaxy (frame)) Yoffset[column]= Yoffset[column] +Height Column= Column >= (NumberOfColumns-1) ?0: ++column} }}
Continue to take on an article, in Preparelayout () This calculation item frame is the core of the entire layout, so must be read every paragraph to understand the core of uicollectionviewlayout.
I explained that in this layout, the concept of the so-called column is manually added. In CollectionView, there is no such column of vertical row, only section and item (that is, row). And the arrangement is always left to right, and one row fills the next line.
The y-axis of our second item depends on the height of the No. 0 item, so you can also consider that the y-axis of an even number item is always relative to the height of the last even item. The odd item is similar.
So, how does the author calculate it?
He took another way, declaring a yoffset array with only two numeric values. Yoffset[0] Record the height of the previous item of the second column in the first column of the previous item's height,yoffset[1] record.
When the For loop goes to the first column of item (that is, the index is even-numbered item), he goes to yoffset[0] and goes to the second column of item (the index is an odd item) and goes to yoffset[1] to get it.
Column is the author used to determine whether the current loop goes to the item is the first column or the second column.
Don't believe it?
1 0 : ++column
Let's take a walk. The column declaration is assigned a value of 0. After the first for loop has gone, the judgment is
1 0: ++column
So when the first cycle is over, column becomes 1, indicating the second time to get a value from yoffset[1]. Do you understand? Then each time the loop, the column will change between 0 and 1.
Actually understand this sentence, the other is no difficulty, nothing is to get the picture height from delegate, text title height, text content height, add up, is each item's height, and then according to this item is the first column, to put into the Yoffset array on the line.
Finally, each layoutattributes is stored in an array for later judgment and reading. No further calculations are needed.
Returns the contentsize of the layout
In the For loop, we make this judgment once every time we execute it.
Contentheight = Max (Contentheight, Cgrectgetmaxy (frame))
In fact, the height of cotnentsize is not the last cell of the Cgrectgetmaxy (frame). So you can calculate that.
override func collectionviewcontentsize ()- cgsize { return cgsize (width: Contentwidth, Height:contentheight)}
Rewrite Layoutattributesforelementsinrect (_:)
override func Layoutattributesforelementsinrect (rect:cgrect), [Anyobject]? { = [Uicollectionviewlayoutattributes] () for attributes in Cache { if cgrectintersectsrect (attributes.frame, rect) { layoutattributes.append ( attributes) } } }return layoutattributes}
The meaning of this method has been mentioned in my last article, that is, every time CollectionView scrolls to an area, CollectionView needs to know the layoutattributes of each cell in this area.
Then we'll use the Cgrectintersectsrect method to traverse to determine which attributes frame is in this area, and then return to CollectionView on the line.
A proxy method to get the height of photo
func CollectionView (Collectionview:uicollectionview, Heightforphotoatindexpath Indexpath:nsindexpath, - cgfloat { = Photos[indexpath.item] = 00, Width: width, height:cgfloat (maxfloat)) let rect = Avmakerectwithaspectratioinsiderect ( Photo.image.size, Boundingrect) return rect.size.height }
This proxy method calculates the height of an image after it has been compressed in the Uiimageview of Contentmode for Aspectfit. If you can see the Wu Yun Niu x (this ID is really crazy drag cool Diao day) of this blog.
Last step, modify the height of the Uiimageview in our Uicollectionviewcell this constraint
override func applylayoutattributes (layoutattributes:uicollectionviewlayoutattributes!) { super.applylayoutattributes (layoutattributes) if? pinterestlayoutattributes { = attributes.photoheight }}
This is the way to rewrite Collectionviewcell, after each time we assign layoutattributes to our cell, we get our photo height, Then pull the cell's imageviewheightlayoutconstraint a line, change the constant property to Layoutattributes Photoheight in the line.
The end of the project is here
In the next issue, we will lead you to a layout that is fluent in English.
Uicollectionview Custom Layout Tutorial