I just wrote a simple waterfall recently .

The overall thinking may not be perfect .

But it's also an effect .

Don't spray

Ideas : Customize UICollectionViewLayout In fact, you need to return each item Of fram That's all right. .

Let's start with the simple ,width value = (CollectionView The overall width of - Left and right margins - The spacing of each column )/ Number of columns

height = Just scale to the original image

x Need to locate On which column = The left margin + ( Column spacing + width) * The column number of the smallest column

y Always add... Under the column with the lowest column height = Minimum column height + Row spacing

The calculation of the minimum column height needs Calculate the height of each column Compare , The value of the minimum column height is constantly replaced . Initialization should be the value of the top margin .

Because I need to calculate the minimum column height, I define a dictionary .

{ key0:columnHeight0,

key1: columnHeight0

...

}

The number of dictionary elements is determined by column To decide . Each column stores the column height of the current column .

By comparison columnHeight To get the smallest of key , Every time you update this minimum key Corresponding columnHeight That's it

  • Now let's look at the code :

Expose variables and proxies .

Open variables can be set at call time , Generally, that's all ,delegate Used to achieve dynamic height settings

//
// WaterFallLayout.h
// Homework 3
//
// Created by gongwenkai on 2016/12/7.
// Copyright 2016 year gongwenkai. All rights reserved.
// #import <UIKit> @protocol WaterFallLayoutDelegate<NSObject> /// Set the image height
//width by cell Actual width
- (CGFloat) collectionViewHeightAtIndexPath:(NSIndexPath *)indexPath withItemWidth:(CGFloat)width; @end @interface WaterFallLayout : UICollectionViewLayout @property(nonatomic,assign)int column; // Set number of columns
@property(nonatomic,assign)int rowMargin; // Set line spacing
@property(nonatomic,assign)int columnMargin;// Set column spacing
@property(nonatomic,assign)UIEdgeInsets edge;// Set margins
@property(nonatomic,strong)id<WaterFallLayoutDelegate>delegate;
@end

Because our custom layout inherits UICollectionViewLayout.

Each layout calls

// Prepare the layout and do some preparatory work , For example, initialization

- (void)prepareLayout;
// This method is prepareLayout After the call . Each drag calls , It's kind of similar scrollview the .
// Here we need to return a UICollectionViewLayoutAttributes You can put it in an array fram Information
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect ;

Do the preparatory work first : Initialize Dictionary

- (void)prepareLayout {
[super prepareLayout]; // NSLog(@"prepareLayout"); // Initialize Dictionary
for (int i = 0; i < _column; i++) {
[self.maxYDict setObject:[NSNumber numberWithFloat:self.edge.top] forKey:[NSString stringWithFormat:@"%d",i]];
}
self.minKey = @"0"; NSMutableArray *array = [NSMutableArray array];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i = 0; i<count xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed> height) {
minY = height;
self.minKey = [NSString stringWithFormat:@"%d",i];
columnHeight = minY + heightAtt; } else {
columnHeight = height; [self.maxYDict setObject:[NSNumber numberWithFloat:columnHeight] forKey:[NSString stringWithFormat:@"%d",i]]; } } // Set up X,Y coordinate
CGFloat x = self.edge.left + [self.minKey floatValue] * (width + self.columnMargin);
CGFloat y = [[self.maxYDict objectForKey:self.minKey] floatValue] ; // Update the height of the minimum column
[self.maxYDict setObject:[NSNumber numberWithFloat:y+heightAtt] forKey:self.minKey]; UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attrs.frame = CGRectMake(x, y, width, heightAtt); return attrs;
}

After the calculation, you can make layoutAttributesForElementsInRect Set back to layout

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
// NSLog(@"layoutAttributesForElementsInRect"); return self.attrsArray;
}

Finally, we need to rewrite the scope of the content , Height is the largest column height

/*
rewrite Set up collectionViewContentSize
*/
- (CGSize)collectionViewContentSize { // The highest column keyword
int columnHeight = 0;
// The first element is selected by default
float maxY = [[self.maxYDict objectForKey:@"0"] floatValue];
// Find the largest number in the dictionary
for (int i = 0; i < self.maxYDict.allKeys.count; i++) {
float height = [[self.maxYDict objectForKey:[NSString stringWithFormat:@"%d",i]] floatValue];
if (maxY < height) {
// keep maxY Minimum
maxY = height;
// Record key
columnHeight = i;
}
} // Read the highest column
CGFloat maxHeight = [[self.maxYDict objectForKey:[NSString stringWithFormat:@"%d",columnHeight]] floatValue]; return CGSizeMake(0, maxHeight + self.edge.bottom);
}

Be accomplished .

Demo Address

https://github.com/gongxiaokai/WaterFallLayoutDemo

Objectiv-c - UICollectionViewLayout Custom layout - More about waterfall flow

  1. Share in detail UICollectionView Custom layout for ( The waterfall flow , linear , circular …)

    Preface : This article is not about sharing collectionView Detailed use of the tutorial , It's about comparison ’ senior ’ Of collectionView Using skills , Before reading , I think you're already familiar with collectionView Basic use of , ...

  2. Share in detail UICollectionView Custom layout for ( The waterfall flow , linear , circular ...)

    Preface : This article is not about sharing collectionView Detailed use of the tutorial , It's about comparison ' senior ' Of collectionView Using skills , Before reading , I think you're already familiar with collectionView Basic use of , ...

  3. css Layout - The realization of waterfall flow

    One . The basic idea 1. First look at the final renderings : 2. Realization principle : adopt position:absolute( Absolute positioning ) To locate each element , And record the height of the current column for the next dom Calculation of position Two . Code implementation 1. edition ...

  4. js- Achieve multi column layout ( The waterfall flow )

    This paper uses the idea of object-oriented to realize multi column layout ( The waterfall flow ). Of course , Using process oriented can also achieve , Specific renderings and cases are as follows : The specific implementation code is as follows : <!DOCTYPE html> <html lang=&quo ...

  5. css3 Multi column layout waterfall flow loading style

    Saw some website waterfall flow loading , Just to see css3 Multi column properties of , Trying to write a css Waterfall flow for layout . Go straight to the code : <!DOCTYPE html> <html lang="en&qu ...

  6. Customize UICollectionViewLayout The waterfall of the river

    Target effect Because the system provides us with  UICollectionViewFlowLayout The layout class can't achieve the effect of waterfall flow , If we want to achieve The waterfall flow The effect of , You need to customize one  UICollectionViewLay ...

  7. iOS Customize UICollectionViewLayout The waterfall of the river

    Target effect Because the system provides us with  UICollectionViewFlowLayout The layout class can't achieve the effect of waterfall flow , If we want to achieve The waterfall flow The effect of , You need to customize one  UICollectionViewLay ...

  8. iOS Exploration of development UICollectionViewController( 3、 ... and ) -- Use UICollectionView Custom waterfall flow

    The example of the last blog is self-contained UICollectionViewDelegateFlowLayout Based on the layout Demo, Details please see <iOS Exploration of development UICollectionViewControlle ...

  9. iOS Grid layout of waterfall flow

    The code address is as follows :http://www.demodashi.com/demo/14760.html One . Results the preview Two . Determining demand According to the requirement diagram below, the minimum unit of a module is a square , Side length is the width of the screen after removing the margin ...

Random recommendation

  1. WindowManager.LayoutParams Notes

    WindowManager.LayoutParams wlp = new WindowManager.LayoutParams(width, height, WindowManager.LayoutP ...

  2. Eclipse Next use GDT Plugins can't log in GAE &amp; GDT Can't upload JAVA Code

    Update today github In the process of the homepage , Want to use GAE Deploy a Java Web Service to better support the dynamic website ( The key is to take advantage of the free GAE resources ), It turned out that 2 A big question . 1.GDT Plugins can't log in GAE Account error 1: land ...

  3. AudioCapabilities member

    Reference resources :http://www.ajerp.com/Cs/DirectX/Capture/DirectX.Capture.html Using Youdao translation 2.0 AudioCapabilities member Public instance fields ...

  4. Image Transformation in WPF Enter the log title

    Image transformation is a process of rotating and scaling images. Rotating Images There are two ways ...

  5. hdu3341Lost&#39;s revenge(ac automata +dp)

    link Allied dp I did it in the Provincial Games , But this question card memory , Need to put the current state hash once , You can calculate the current state in decimal terms , Because the number of States will not exceed 10*10*10*10 Of , So it's perfectly possible to save these . Just started putting trie ...

  6. CyclicBarrier、CountDownLatch And Semaphore My notes

    CyclicBarrier: Suitable business scenarios , such as 1)., There is a big task , We need to get the statistics of the whole year , This workload is huge , So it can be divided into 12 Three months of subtasks , The subtasks are independent of each other , When all the subtasks are completed , Then ...

  7. 【M1】 Distinguish carefully pointers and references

    1. References must be initialized , And you can't change the direction , This and const The objects are very similar . 2. Reference and pointer usage are different , For quotes int& ri = a; rhs It's an object , The quotation is preceded by &: For the pointer ,int* pi ...

  8. mac My life in the future —— Replace the main drive with ssd

    The most important thing I've done in the past two days is my two hard disks , Basically, they take up all the time , But the final result also makes me happy -- Power on seconds , Program instants , The quality of life has improved a lot in an instant . About ssd All kinds of things , My other blog says , It's a comparison ...

  9. Python The parameter module of OptionParser explain

    Can replace getopt A module of from optparse import OptionParser #   Generate an instance parser = OptionParser(usage="%prog ...

  10. Ext How to send ajax request

    Ext3.3 The whole package Ext3.3 Chinese document The structure of the data table is : Data sheet table  > Record record > Field store The structure of is :  Ext.data.Store > Ext.dat ...