IOS Waterfall Stream Uicollectionview implementation

Source: Internet
Author: User

IOS Waterfall Stream Uicollectionview implementation

Take a look at the embryonic shape of the waterfall stream before realizing the waterfall flow (the embryonic uicollectionview of this method)

We have a few caveats for Uicollectionview.

    • It is not the same as TableView, the content of Contentview completely need our own to add.
    • Compared to TableView, his initialization needs to be flowlayout and most of the operations on it.
    • Uicollectionview is very practical, although sometimes he is not the best solution, but it can be very flexible to achieve a variety of effects.

Figure (i)

, the simulator shows a lot of squares, but it's worth noting that they have rules.

Although it looks neat but not beautiful.

What we are talking about is to achieve the waterfall flow is to achieve its untidy, but the law (here I say the law)

Business

The front says that most of Uicollectionview's operations are on FlowLayout, and of course the pattern deployment.

What we're going to achieve in order to achieve waterfall flow is to change his pattern deployment.

Make sure you realize the idea before you write the code.
    • What do you need???
      • First we need to determine the display style of the waterfall flow.
      • Then the overall design is based on a well-defined style.
      • Finally complete the code through the details of the process
        • What kind of style do we need???
          • What we need is an effect that changes the layout in the above image to a different height.
          • The vulgar point is like a name, like waterfall water.
        • How to design the whole???
          • The overall use of the same design method as the above picture, each module is a cell
          • Make sure the cell on the top row has the same Y value (beautiful)
          • Make sure you don't get a particularly long column with a particularly short effect
        • What are the preliminary details???
          • Because the height of each cell is different, we have to consider what the order of placement should be
          • Thin code (this is what each project must be aware of)
Achieve results

Code

Here is the code part of the implementation (not provided demo is very simple)

I'll briefly describe it in the comments.

---

////VIEWCONTROLLER.M//cx-Waterfall Flow uicollectionview Realization////Created by Ma C on 16/4/8.//copyright©2016 year BJSXT. All rights reserved.//#import"ViewController.h"#import"CXCollectionViewCell.h"#import"CXCollectionViewLayout.h"StaticNSString * identifier =@"Cellid"; @interface Viewcontroller ()<UICollectionViewDataSource>//The Uicollectionview to show@property (nonatomic, strong) Uicollectionview *CollectionView, @end @implementation viewcontroller#pragmaMark-< Lazy load >-(Uicollectionview *) CollectionView {if(!_collectionview) {        //Initialize our custom FlowLayoutCxcollectionviewlayout * FlowLayout =[[Cxcollectionviewlayout alloc]init]; //Initialize CollectionView_collectionview =[[Uicollectionview alloc]initwithframe:self.view.bounds collectionviewlayout:flowlayout]; //set up a data source (CollectionView's lifeblood)_collectionview.datasource =Self ; //Sign up for our custom cell[_collectionview registernib:[uinib Nibwithnibname:nsstringfromclass ([Cxcollectionviewcellclass]) Bundle:nil] forcellwithreuseidentifier:identifier]; }    return_collectionview;}#pragmaMark-<life>-(void) viewdidload {[Super viewdidload]; //Add---On the self.view[Self.view AddSubview:self.collectionView];}#pragmaMark-<UICollectionViewDataSource>//This returns the number of item returned-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberofitemsinsection: (nsinteger) section{return  -;}//the cell is returned here, and we can do some simple things here.-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) indexpath{Cxcollectionviewcell* Cell =[CollectionView dequeuereusablecellwithreuseidentifier:identifier Forindexpath:indexpath]; //for the implementation details of the waterfall flow we added the labelCell.label.text= [NSString stringWithFormat:@"%zd", Indexpath.item]; //background color of cellCell.backgroundcolor =[Uicolor Orangecolor]; returnCell;} @end

---

////CXCOLLECTIONVIEWLAYOUT.M//cx-Waterfall Flow uicollectionview Realization////Created by Ma C on 16/4/8.//copyright©2016 year BJSXT. All rights reserved.//#import"CXCollectionViewLayout.h"//number of columns in the waterfall streamStaticNsinteger Cxcolumncount =3;//the inner margin of the waterfall flowStaticUiedgeinsets cxdefaultedgeinsets = { -, the,Ten, the};//column spacing for cellsStaticNsinteger Cxcolumnmagin =Ten;//row spacing for cellsStaticNsinteger Cxrowmagin =Ten; @interface cxcollectionviewlayout ()//Store layout properties for all cells@property (nonatomic, strong) Nsmutablearray *Cxattrsarray;//scale the height of all columns@property (nonatomic, strong) Nsmutablearray *cxcolumnheights, @end @implementation cxcollectionviewlayout#pragmaMark-< Lazy load >-(Nsmutablearray *) cxattrsarray{if(!_cxattrsarray) {_cxattrsarray=[Nsmutablearray array]; }    return_cxattrsarray;}-(Nsmutablearray *) cxcolumnheights{if(!_cxcolumnheights) {_cxcolumnheights=[Nsmutablearray array]; }    return_cxcolumnheights;}#pragmaMark-< Prepare layouts >//Prepare the layout (automatic execution before layout)- (void) preparelayout{//Override this method to remember Super[Super Preparelayout]; //Our data is not fixed in practice, so it is best to empty the previously stored properties before each layout .//empty the height of all columns//empty the non-go attribute for all cells[Self.    Cxcolumnheights Removeallobjects]; [Self.    Cxattrsarray Removeallobjects]; //first, the cell in the first row is attached to the height     for(Nsinteger i =0; i < Cxcolumncount; i + +) {        //only objects can be stored in an array[Self.    Cxcolumnheights addobject:@ (cxdefaultedgeinsets.top)]; }    //The following begins to create a layout property for each cell and adds it to the array that stores the cell layout properties//Total cell count because there's only one section here .Nsinteger count = [Self.collectionview numberofitemsinsection:0];  for(Nsinteger i =0; I < count; i + +) {        //Create location is IndexpathNsindexpath * Indexpath = [Nsindexpath indexpathforitem:i insection:0]; //get the cell layout properties for IndexpathUicollectionviewlayoutattributes * attributes =[self layoutattributesforitematindexpath:indexpath]; //Add the acquired layout property to the array[Self.    Cxattrsarray Addobject:attributes]; }    //The job of preparing the layout is over here.}//returns all cell layout properties and the arrangement of the whole cell-(nsarray<uicollectionviewlayoutattributes *> *) Layoutattributesforelementsinrect: (cgrect) rect{returnSelf . Cxattrsarray;}//returns the layout properties of a cell-(Uicollectionviewlayoutattributes *) Layoutattributesforitematindexpath: (Nsindexpath *) indexpath{//Create layout PropertiesUicollectionviewlayoutattributes * Cxattributes =[Uicollectionviewlayoutattributes Layoutattributesforcellwithindexpath:indexpath]; //gets the width of the CollectionViewCGFloat collectionviewwidth =Self.collectionView.frame.size.width; //The following section gets the cell's frame (layout properties)cgfloat width;    CGFloat height;    CGFloat X;    CGFloat Y; //Get widthwidth = (Collectionviewwidth-cxdefaultedgeinsets.left-cxdefaultedgeinsets.right-(Cxcolumncount-1) * Cxcolumnmagin)/Cxcolumncount; //Get Height//in the actual development of the heigh is not really random but based on the data to determine the height here to show the preliminary introduction of its principle and therefore the use of more than 100 less than 150 random numberHeight = -+ Arc4random_uniform ( -); //get X (the implementation of the waterfall stream is focused on the X, Y value of the cell)//set an intermediate variable for a number of columnsNsinteger Tempcolumn =0; //set the middle variable with a small height here we give him the height of the No. 0 column, which will reduce the number of cycles and increase efficiency.CGFloat mincolumnheight = [self. cxcolumnheights[0] Doublevalue];  for(Nsinteger i =1; i < Cxcolumncount; i + +) {        if(Mincolumnheight >[Self. Cxcolumnheights[i] Doublevalue]) {mincolumnheight=[Self.            Cxcolumnheights[i] Doublevalue]; Tempcolumn=i; }} X= Cxdefaultedgeinsets.left + (width + cxcolumnmagin) *Tempcolumn; //Get yY =Mincolumnheight; if(Y! =cxdefaultedgeinsets.top) {Y+=Cxrowmagin; }    //set the cell's frameCxattributes.frame =CGRectMake (X, Y, width, height); //Update the height of the height of the shortest columnSelf. Cxcolumnheights[tempcolumn] =@ (Cgrectgetmaxy (cxattributes.frame)); returncxattributes;}//returns the size of the content of the Collegeview-(cgsize) collectionviewcontentsize{//Although the return size, but our main here is the heightCGFloat maxcolumnheight = [self. cxcolumnheights[0] Doublevalue];  for(Nsinteger i =1; i < Cxcolumncount; i++) {cgfloat columnheight=[Self.                Cxcolumnheights[i] Doublevalue]; if(Maxcolumnheight <columnheight) {Maxcolumnheight=Columnheight; }    }    returnCgsizemake (0, Maxcolumnheight +cxdefaultedgeinsets.bottom); } @end

The realization of the waterfall flow is ended.

Here are some noteworthy points to note.

    • The cell arrangement in the waterfall flow is based on the height of the current column (for example, if the current third column is the shortest, but normally the cell should be in the first column, then the new cell will be in the third column, in order to avoid a column with a particularly long height or a column with a particularly short height)
    • In practice, the size of the cell is usually handled according to the data.
    • The height of the content of Uicollectionview is uncertain, so we have to set the height according to the contents.
    • When it comes to refreshing, we need to be aware that the cell layout properties are emptied before the new data arrives.

IOS Waterfall Stream Uicollectionview implementation

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.