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 Stream Uicollectionview implementation////Created by Ma C on 16/4/8.//Copyright? 2016 BJSXT. All rights reserved.//#import "ViewController.h" #import "CXCollectionViewCell.h" #import "CXCollectionViewLayout.h" static NSString * identifier = @ "Cellid"; @interface Viewcontroller () <uicollectionviewdatasource>// The Uicollectionview@property to be shown (nonatomic, strong) Uicollectionview * CollectionView; @end @implementation Viewcontroller#pragma mark-< lazy load >-(Uicollectionview *) CollectionView {if (!_collectionview) {//Initialize our custom        The Righteous flowlayout cxcollectionviewlayout * FlowLayout = [[Cxcollectionviewlayout alloc]init]; Initialize CollectionView _collectionview = [[Uicollectionview alloc]initwithframe:self.view.bounds CollectionViewLayout:        FlowLayout];        Set the data source (CollectionView's lifeblood) _collectionview.datasource = self; Register our custom cell [_collectionview registernib:[uinib nibwithnibname:nsstringfromclass ([Cxcollectionviewcell class])Bundle:nil] Forcellwithreuseidentifier:identifier]; } return _collectionview;}    #pragma mark-<life>-(void) viewdidload {[Super viewdidload]; Add---on Self.view [Self.view AddSubview:self.collectionView];} #pragma mark-<uicollectionviewdatasource>//returns the number of item returned 100-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberofitemsinsection: (nsinteger) section{return 100;} This returns the cell we can do some simple operations here-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (Nsindexpath *) indexpath{Cxcollectionviewcell * cell = [CollectionView DequeueReusableCellW    Ithreuseidentifier:identifier Forindexpath:indexpath];    For the implementation details of the waterfall flow we added the label cell.label.text = [NSString stringwithformat:@ "%zd", Indexpath.item];        Cell background Color Cell.backgroundcolor = [Uicolor Orangecolor]; return cell;} @end

---

cxcollectionviewlayout.m//cx-Waterfall Stream Uicollectionview implementation////Created by Ma C on 16/4/8.//Copyright? 2016 BJSXT. All rights reserved.//#import the number of columns in the "CXCollectionViewLayout.h"//Waterfall stream static Nsinteger Cxcolumncount = 3;//The inner margin of the waterfall stream static Uiedgeinsets cxdefaultedgeinsets = {20,15,10,15};//cell column spacing static nsinteger cxcolumnmagin = 10;//cell line spacing static Nsinteger cxrowmagin = ten; @interface cxcollectionviewlayout ()//Store layout properties of all cells @property (nonatomic, Strong) Nsmutablearray * cxattrsarray;//Scale the height of all columns @property (nonatomic, Strong) Nsmutablearray * cxcolumnheights;@ End@implementation Cxcollectionviewlayout#pragma mark-< lazy load >-(Nsmutablearray *) cxattrsarray{if (!_CXattrsArra    Y) {_cxattrsarray = [Nsmutablearray array]; } return _cxattrsarray;}    -(Nsmutablearray *) cxcolumnheights{if (!_cxcolumnheights) {_cxcolumnheights = [Nsmutablearray array]; } return _cxcolumnheights;} #pragma mark-< prepare layout >//prepare layout (automatic execution before layout)-(void) preparelayout{//Override this method be sure to remember super [Super Preparelayout]; In practice our data is not fixed, so we'd better clear the previously stored properties before each layout//empty the height of all columns//Empty the non-go property of all cells [self].    Cxcolumnheights Removeallobjects]; [Self.    Cxattrsarray Removeallobjects]; First the cell with the first row is attached height for (Nsinteger i = 0; i < cxcolumncount; i + +) {//array can only hold object [self].    Cxcolumnheights addobject:@ (cxdefaultedgeinsets.top)]; }//below start creating the layout properties for each cell and add the total number of//cell to the array that stores the cell layout properties because there is only one section nsinteger count = [Self.collectionview Numbe    ROFITEMSINSECTION:0]; for (Nsinteger i = 0; i < count; i + +) {//Create location indexpath nsindexpath * Indexpath = [Nsindexpath indexp        Athforitem:i insection:0]; Get Indexpath corresponding Cell layout property uicollectionviewlayoutattributes * attributes = [self layoutattributesforitematindexpath:i        Ndexpath]; Adds the acquired layout property to the array [self.    Cxattrsarray Addobject:attributes]; }//Prepare the layout of the work is over here.}//returns all cell layout properties and overall cell arrangement-(nsarray<uicollectionviewlayoutattributes *> *) LayoutattributesforelemeNtsinrect: (cgrect) rect{return self. Cxattrsarray;} Returns the layout properties of the cell-(uicollectionviewlayoutattributes *) Layoutattributesforitematindexpath: (Nsindexpath *) indexPath{// Create Layout Properties Uicollectionviewlayoutattributes * cxattributes = [uicollectionviewlayoutattributes        Layoutattributesforcellwithindexpath:indexpath];    Get collectionview wide cgfloat collectionviewwidth = self.collectionView.frame.size.width;    The following section is to get the cell's frame (layout property) CGFloat width;    CGFloat height;    CGFloat X;    CGFloat Y; Get width width = (collectionviewwidth-cxdefaultedgeinsets.left-cxdefaultedgeinsets.right-(CXcolumnCount-1) * C    Xcolumnmagin)/Cxcolumncount; Get height//in the actual development heigh is not really random but based on the data to determine the height here to show the preliminary introduction of its principle so that the use of a random number greater than 100 less than 150 height = + arc4random_uniform (    50);    Get X (the implementation of the waterfall stream is focused on the X, Y value of the cell)//Set the middle variable of a number of columns Nsinteger tempcolumn = 0; Set the middle variable with a small height here we give him the height of the No. 0 column, which can reduce the number of cycles and improve 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 y y = mincolumnheight;    if (Y! = cxdefaultedgeinsets.top) {y + = Cxrowmagin;    }//Set the cell's frame cxattributes.frame = CGRectMake (X, Y, width, height); The height of the height of the shortest column is updated self.        Cxcolumnheights[tempcolumn] = @ (Cgrectgetmaxy (cxattributes.frame)); return cxattributes;} Returns the size of the content of the Collegeview-(cgsize) collectionviewcontentsize{//Although the size is returned, but our main here is the height cgfloat maxcolumnheight = [Self.    Cxcolumnheights[0] Doublevalue]; for (Nsinteger i = 1; i < Cxcolumncount; i++) {CGFloat columnheight = [self].                Cxcolumnheights[i] Doublevalue];        if (Maxcolumnheight < columnheight) {maxcolumnheight = Columnheight; }} RETurn cgsizemake (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

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.