Ios:uicollectionview Pure Custom layout: Waterfall Flow Layout

Source: Internet
Author: User
Tags uikit

There are three ways of creating a waterfall stream:

 The first way: In a scrollview inside put three cell height of the same tableview, prohibit tableview scrolling, just let tableview with ScrollView scroll. This way is too wonderful, not recommended to use ... the second way: in a scrollview inside from left to right into three uiview, when the ScrollView scroll, if the previous three view disappears will be stored in the custom buffer pool, that is, the array, Drop-down and then remove the three view from the array below the previous three view positions. However, remember that each time you want to calculate the shortest, in order to prevent the distance between the more and more ..., this way a little more trouble ... The Third way: In fact, the second simple version of the above, is the use of Uicollectionview, because it has its own reuse mechanism, we only need to do is to calculate the next cell location can .... Automatic layout of the collection view: Uicollectionviewlayout is an abstract root class, you must use its subclasses to create an instance, the following is the overridden method, which evaluates the item's layout properties

Layouts are prepared before each re-layout (Apple recommends using this method for some initialization)

-(void) preparelayout

Override Layoutattributesforitematindexpath to return the layout properties of each item (flow layout has been helped to complete)

-(Uicollectionviewlayoutattributes *) Layoutattributesforitematindexpath: (Nsindexpath *) IndexPath

Whether you want to refresh the layout again (re-layout as soon as the item boundary of the display changes)

As long as each re-layout is internally called the following layoutattributesforelementsinrect: Gets the properties of all cell (item)

-(BOOL) Shouldinvalidatelayoutforboundschange: (CGRect) newbounds

Returns all item properties that need to be re-laid

-(nsarray*) Layoutattributesforelementsinrect: (cgrect) rect

?? : The following waterfall flow layout can be removed directly using

The following waterfall stream code is created using the third method:

WaterFlowLayout.h

#Import<UIKit/UIKit.h>/*in order to embody the characteristics of encapsulation, we can set some data to public, not only can improve the expansibility and universality, but also facilitate the outside world to make the necessary adjustments according to their own needs. */@protocol waterflowlayoutdelegate;//set the proxy to pass data, reduce the coupling with other classes, more versatility@classwaterflowlayout;@InterfaceWaterflowlayout:uicollectionviewlayout@property (assign,nonatomic) cgfloat columnmargin;//the spacing between each column item@property (assign,nonatomic) cgfloat rowmargin;//the spacing between each line item@property (assign,nonatomic) uiedgeinsets sectioninset;//spacing set at the edge of the CollectionView@property (assign,nonatomic) Nsinteger ColumnCount;//set the number of rows for each row@property (weak,nonatomic) ID<WaterFlowLayoutDelegate> delegate;//Set up proxy@end @protocol waterflowlayoutdelegate-(CGFloat) Waterflowlayout: (Waterflowlayout *) waterflowlayout heightforwidth: (cgfloat) Width Andindexpath: ( Nsindexpath *) Indexpath; @end

WATERFLOELAYOUT.M

#Import"WaterFlowLayout.h"//the spacing between each column item//static const CGFloat columnmargin = ten;//the spacing between each line item//static const CGFloat rowmargin = ten;@Interfacewaterflowlayout ()/**This dictionary is used to store the height of each column of item*/@property (strong,nonatomic) nsmutabledictionary*Maxydic;/**store Layout properties for each item*/@property (strong,nonatomic) Nsmutablearray*Attrsarray, @end @implementation waterflowlayout/**Lazy Loading*/-(Nsmutabledictionary *) maxydic{if(!_maxydic) {_maxydic=[Nsmutabledictionary dictionary]; }    return_maxydic;}/**Lazy Loading*/-(Nsmutablearray *) attrsarray{if(!_attrsarray) {_attrsarray=[Nsmutablearray array]; }    return_attrsarray;}//Initialize-(instancetype) init{if(self = [SuperInit]) {Self.columnmargin= 10; Self.rowmargin= 10; Self.sectioninset= Uiedgeinsetsmake (10, 10, 10, 10); Self.columncount= 3; }    returnSelf ;}//preparation before each layout-(void) preparelayout{[SuperPreparelayout]; //clears the maximum Y value     for(inti = 0; i < Self.columncount; i++) {NSString*column = [NSString stringwithformat:@ "%d", I]; Self.maxydic[column]=@ (self.sectionInset.top); }    //Calculate properties for all item[Self.attrsarray removeallobjects]; Nsinteger Count= [Self.collectionview numberofitemsinsection:0];  for(inti=0; i<count; i++) {uicollectionviewlayoutattributes*attrs = [Self Layoutattributesforitematindexpath:[nsindexpath indexpathforitem:i insection:0]];    [Self.attrsarray Addobject:attrs]; }}//Setting the CollectionView scrolling area-(cgsize) collectionviewcontentsize{//assuming the longest column No. 0__block nsstring *maxcolumn = @ "0"; //traverse the dictionary to find the longest column[Self.maxydic enumeratekeysandobjectsusingblock:^ (NSString *column, NSNumber *maxy, BOOL *stop) {                if([Maxy Floatvalue] >[Self.maxydic[maxcolumn] floatvalue]) {Maxcolumn=column;    }    }]; returnCgsizemake (0, [self.maxydic[maxcolumn]floatvalue]+self.sectionInset.bottom);}//allow re-layout every time-(BOOL) Shouldinvalidatelayoutforboundschange: (cgrect) newbounds{returnYES;}//Layout each property-(Uicollectionviewlayoutattributes *) Layoutattributesforitematindexpath: (Nsindexpath *) indexpath{//assuming the shortest column No. 0__block nsstring *mincolumn = @ "0"; //traverse the dictionary to find the shortest column[Self.maxydic enumeratekeysandobjectsusingblock:^ (NSString *column, NSNumber *maxy, BOOL *stop) {                if([Maxy Floatvalue] <[Self.maxydic[mincolumn] floatvalue]) {Mincolumn=column;        }    }]; //Calculate the width and height of each itemCGFloat width = (self.collectionview.frame.size.width-self.columnmargin* (self.columncount-1)- Self.sectioninset.left-self.sectioninset.right)/Self.columncount; CGFloat height=[self.delegate waterflowlayout:self heightforwidth:width Andindexpath:indexpath]; //calculate the location of each itemCGFloat x = self.sectionInset.left + (width + self.columnmargin) *[Mincolumn Floatvalue]; CGFloat y= [Self.maxydic[mincolumn] floatvalue] +Self.rowmargin; //Update the Y value of this columnSelf.maxydic[mincolumn] = @ (y +height); //Create layout PropertiesUicollectionviewlayoutattributes *attrs =[Uicollectionviewlayoutattributes Layoutattributesforcellwithindexpath:indexpath]; //Set Item's frameAttrs.frame =CGRectMake (x, y, width, height); returnattrs;}//layout The properties of all item, including header, footer-(Nsarray *) Layoutattributesforelementsinrect: (cgrect) rect{returnSelf.attrsarray;} @end

The waterfall Flow demo results are as follows:

Ios:uicollectionview Pure Custom layout: Waterfall Flow Layout

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.