iOS Flow Layout Uicollectionview Series four--custom flowlayout for waterfall flow layout

Source: Internet
Author: User

iOS Flow Layout Uicollectionview Series four--custom flowlayout for waterfall flow layoutFirst, Introduction

The first few blogs from Uicollectionview to Settings uicollectionviewflowlayout more flexible layout, but are limited to the system for us to prepare the layout framework, there are some limitations, for example, If I'm going to do a waterfall-like high-level layout, the previous approach will be difficult to meet our needs, as follows:

This layout is undoubtedly more extensive in the application of the app, the product display, Bookshelf Bibliography display, will tend to adopt such layout way, of course, through the custom FlowLayout, we are also easy to implement.

Second, a custom waterfall flow layout

First, we create a new file that inherits from Uicollectionviewflowlayout:

@interface Mylayout:uicollectionviewflowlayout

In order to demonstrate the aspect, here I am good more encapsulation, add a property, directly let the outside world to pass the item number in, we put the center of gravity method to rewrite the layout method:

@interface Mylayout:uicollectionviewflowlayout@property (nonatomic,assign) int itemCount; @end

As I said earlier, Uicollectionviewflowlayout is a class designed to manage CollectionView layouts, so CollectionView will get the relevant layout information through objects of this class before the UI layout. The FlowLayout class stores all of these layout information in an array, which is the Uicollectionviewlayoutattributes class, which is the specific setting for the item layout and we are discussing this class later. In summary, the FlowLayout class places layout information, such as the location of each item, in an array that, when CollectionView layout, calls the FlowLayout class Layoutattributesforelementsinrect: Method to get this layout configuration array. Therefore, we need to rewrite this method to return our custom array of configurations, and the FlowLayout class will call the Preparelayout method before it is laid out, so we can override this method to set some of our custom configuration data inside.

To put it simply, customizing a FlowLayout layout class is a two-step process:

1, the design of our layout configuration data preparelayout method

2. Return to our configuration array Layoutattributesforelementsinrect method

The sample code is as follows:

@implementation  mylayout{    //This array is our custom layout configuration array      Nsmutablearray * _attributeattay;} The relative setting of the array in this method//pre-layout will call this method-(void) preparelayout{    _attributeattay = [[ nsmutablearray alloc]init];    [super preparelayout];    // Demo Convenience   We set the static 2 column     //to calculate the width of each item     float width =   ([Uiscreen mainscreen]. bounds.size.width-self.sectioninset.left-self.sectioninset.right-self.minimuminteritemspacing)/2;     //define an array to hold the height of each column     //the main purpose of this array is to save the total height of each column so that we can always place the next item below the shortest column in the layout      CGFloat colHight[2]={self.sectionInset.top,self.sectionInset.bottom};     //itemcount is the number of items passed in from outside the world   always set the layout of each item     for  (int i=0; i< _itemcount; i++)  {      &nbsp //set the location of each item and other related properties         nsindexpath *index = [ nsindexpath indexpathforitem:i insection:0];        // Create a layout property class that is created by Indexpath         UICollectionViewLayoutAttributes  * attris = [uicollectionviewlayoutattributes layoutattributesforcellwithindexpath:index];         //Random One height   between 40--190          cgfloat hight = arc4random ()%150+40;         //which column height   is placed under that column         //the column with the shortest Mark          int width=0;        if  (Colhight[0] &LT;COLHIGHT[1])  {            // Add a new item height to the short column             colhight[0] = colhight[0]+hight+ self.minimumlinespacing;            width=0;         }else{             colHight[1] = colHight[1]+hight+self.minimumLineSpacing;             width=1;        }                 //Setting the item location          attris.frame = cgrectmake (self.sectionInset.left+ ( Self.minimuminteritemspacing+width) *width, colhight[width]-hight-self.minimumlinespacing, width,  hight);        [_attributeattay addobject:attris];     }        //set ItemSize to ensure that the sliding range is correct   here is calculated by averaging all the item height (with the highest yours faithfully standard)     if  ( COLHIGHT[0]&GT;COLHIGHT[1])  {        self.itemSize =  Cgsizemake (width,  (colhight[0]-self.sectioninset.top) *2/_itemcount-self.minimumlinespacing);     }else{          self.itemSize =  Cgsizemake (width,  (colhight[1]-self.sectioninset.top) *2/_itemcount-self.minimumlinespacing);     }    }//returns our layout array in this method-(nsarray<uicollectionviewlayoutattributes *>  *) Layoutattributesforelementsinrect: (CGRect) Rect{    return _attributeattay;} @end

after customizing the FlowLayout, we use it in Viewcontroller:

-  (void) viewdidload {    [super viewdidload];    //  Do any additional setup after loading the view, typically  From a nib.    mylayout * layout = [[mylayout alloc] init];    layout.scrolldirection = uicollectionviewscrolldirectionvertical;     layout.itemCount=100;     UICollectionView *  Collect  = [[uicollectionview alloc]initwithframe:cgrectmake (0, 0, 320, 400 )  collectionViewLayout:layout];    collect.delegate=self;     collect.datasource=self;        [collect registerclass:[ uicollectionviewcell class] forcellwithreuseidentifier:@ "Cellid"];       [self.view addsubview:collect];        }-(Nsinteger) Numberofsectionsincollectionview: (UICollectionView  *) collectionview{    return 1;} -(Nsinteger) CollectionView: (uicollectionview *) Collectionview numberofitemsinsection: (NSInteger) section{    return 100;} -(uicollectionviewcell *) CollectionView: (uicollectionview *) collectionview  Cellforitematindexpath: (nsindexpath *) indexpath{    uicollectionviewcell *  cell  = [collectionview dequeuereusablecellwithreuseidentifier:@ "Cellid"  forIndexPath : Indexpath];    cell.backgroundcolor = [uicolor colorwithred:arc4random ()% 255/255.0 green:arc4random ()%255/255.0 blue:arc4random ()%255/255.0 alpha:1];     return cell;}

The effect of the operation is in our introduction.

III. Properties We can configure in the Uicollectionviewlayoutattributes class

From the above example, we can understand that the CollectionView item layout is actually configured by the Layoutattributes class, and this class can be configured with a layout property that is more than just a frame, with many properties:

Configure the layout location of item @property  (nonatomic)  cgrect frame;//Configure the center of the item @property  (nonatomic)   cgpoint center;//Configure the size of item @property  (nonatomic)  cgsize size;//Configure the item's 3D effect @property  ( nonatomic)  catransform3d transform3d;//Configuration item bounds@property  (nonatomic)  CGRect  Bounds ns_available_ios (7_0);//configuration Item Rotation @property  (nonatomic)  cgaffinetransform transform  ns_available_ios (7_0);//configuration Item alpha@property  (nonatomic)  cgfloat alpha;// Configure the z-coordinate of item @property  (nonatomic)  nsinteger zindex; // default is 0// Configure the item's hidden @property  (Nonatomic, getter=ishidden)  bool hidden; // Item indexpath@property  (Nonatomic, strong)  nsindexpath *indexpath;//Gets the type of item @property   (nonatomic, readonly)  UICollectionElementCategory representedElementCategory; @property   (nonatomic, readonly, nullable)  nsstring *representedelementkind; //Some creation methods +  (Instancetype) Layoutattributesforcellwithindexpath: (NSIndexPath  *) indexpath;+  (instancetype) Layoutattributesforsupplementaryviewofkind: (nsstring *) elementKind  Withindexpath: (nsindexpath *) indexpath;+  (instancetype) Layoutattributesfordecorationviewofkind: ( nsstring *) Decorationviewkind withindexpath: (nsindexpath *) Indexpath;

Through the above properties, you can lay out a variety of cool effects, as a sentence: no, only unexpected.

iOS Flow Layout Uicollectionview Series four--custom flowlayout for 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.