iOS流布局UICollectionView系列四——自訂FlowLayout進行瀑布流布局

來源:互聯網
上載者:User

標籤:

iOS流布局UICollectionView系列四——自訂FlowLayout進行瀑布流布局 一、引言

        前幾篇部落格從UICollectionView的基礎應用到設定UICollectionViewFlowLayout更加靈活的進行布局,但都限制在系統為我們準備好的布局架構中,還是有一些局限性,例如,如果我要進行瀑布流似的不定高布局,前面的方法就很難滿足我們的需求了,如下:

這種布局無疑在app的應用中更加廣泛,商品的展示,書架書目的展示,都會傾向於採用這樣的布局方式,當然,通過自訂FlowLayout,我們也很容易實現。

二、進行自訂瀑布流布局

        首先,我們建立一個檔案繼承於UICollectionViewFlowLayout:

@interface MyLayout : UICollectionViewFlowLayout

為了示範的方面,這裡我不錯更多的封裝,添加一個屬性,直接讓外界將item個數傳遞進來,我們把重心方法重寫布局的方法上:

@interface MyLayout : UICollectionViewFlowLayout@property(nonatomic,assign)int itemCount;@end

前面說過,UICollectionViewFlowLayout是一個專門用來管理collectionView布局的類,因此,collectionView在進行UI布局前,會通過這個類的對象擷取相關的布局資訊,FlowLayout類將這些布局資訊全部存放在了一個數組中,數組中是UICollectionViewLayoutAttributes類,這個類是對item布局的具體設定,以後咱們在討論這個類。總之,FlowLayout類將每個item的位置等布局資訊放在一個數組中,在collectionView布局時,會調用FlowLayout類layoutAttributesForElementsInRect:方法來擷取這個布局配置數組。因此,我們需要重寫這個方法,返回我們自訂的配置數組,另外,FlowLayout類在進行布局之前,會調用prepareLayout方法,所以我們可以重寫這個方法,在裡面對我們的自訂配置資料進行一些設定。

簡單來說,自訂一個FlowLayout布局類就是兩個步驟:

1、設計好我們的布局配置資料 prepareLayout方法中

2、返回我們的配置數組 layoutAttributesForElementsInRect方法中

範例程式碼如下:

@implementation MyLayout{    //這個數組就是我們自訂的布局配置數組    NSMutableArray * _attributeAttay;}//數組的相關設定在這個方法中//布局前的準備會調用這個方法-(void)prepareLayout{    _attributeAttay = [[NSMutableArray alloc]init];    [super prepareLayout];    //示範方便 我們設定為靜態2列    //計算每一個item的寬度    float WIDTH = ([UIScreen mainScreen].bounds.size.width-self.sectionInset.left-self.sectionInset.right-self.minimumInteritemSpacing)/2;    //定義數組儲存每一列的高度    //這個數組的主要作用是儲存每一列的總高度,這樣在布局時,我們可以始終將下一個Item放在最短的列下面    CGFloat colHight[2]={self.sectionInset.top,self.sectionInset.bottom};    //itemCount是外界傳進來的item的個數 遍曆來設定每一個item的布局    for (int i=0; i<_itemCount; i++) {        //設定每個item的位置等相關屬性        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];        //建立一個布局屬性類,通過indexPath來建立        UICollectionViewLayoutAttributes * attris = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];        //隨機一個高度 在40——190之間        CGFloat hight = arc4random()%150+40;        //哪一列高度小 則放到那一列下面        //標記最短的列        int width=0;        if (colHight[0]<colHight[1]) {            //將新的item高度加入到短的一列            colHight[0] = colHight[0]+hight+self.minimumLineSpacing;            width=0;        }else{            colHight[1] = colHight[1]+hight+self.minimumLineSpacing;            width=1;        }                //設定item的位置        attris.frame = CGRectMake(self.sectionInset.left+(self.minimumInteritemSpacing+WIDTH)*width, colHight[width]-hight-self.minimumLineSpacing, WIDTH, hight);        [_attributeAttay addObject:attris];    }        //設定itemSize來確保滑動範圍的正確 這裡是通過將所有的item高度平均化,計算出來的(以最高的列位標準)    if (colHight[0]>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);    }    }//這個方法中返回我們的布局數組-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{    return _attributeAttay;}@end

自訂完成FlowLayout後,我們在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;}

運行效果就是我們引言中的。

三、UICollectionViewLayoutAttributes類中我們可以配置的屬性

        通過上面的例子,我們可以瞭解,collectionView的item布局其實是LayoutAttributes類具體配置的,這個類可以配置的布局屬性不止是frame這麼簡單,其中還有許多屬性:

//配置item的布局位置@property (nonatomic) CGRect frame;//配置item的中心@property (nonatomic) CGPoint center;//配置item的尺寸@property (nonatomic) CGSize size;//配置item的3D效果@property (nonatomic) CATransform3D transform3D;//配置item的bounds@property (nonatomic) CGRect bounds NS_AVAILABLE_IOS(7_0);//配置item的旋轉@property (nonatomic) CGAffineTransform transform NS_AVAILABLE_IOS(7_0);//配置item的alpha@property (nonatomic) CGFloat alpha;//配置item的z座標@property (nonatomic) NSInteger zIndex; // default is 0//配置item的隱藏@property (nonatomic, getter=isHidden) BOOL hidden; //item的indexpath@property (nonatomic, strong) NSIndexPath *indexPath;//擷取item的類型@property (nonatomic, readonly) UICollectionElementCategory representedElementCategory;@property (nonatomic, readonly, nullable) NSString *representedElementKind; //一些建立方法+ (instancetype)layoutAttributesForCellWithIndexPath:(NSIndexPath *)indexPath;+ (instancetype)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind withIndexPath:(NSIndexPath *)indexPath;+ (instancetype)layoutAttributesForDecorationViewOfKind:(NSString *)decorationViewKind withIndexPath:(NSIndexPath *)indexPath;

通過上面的屬性,可以布局出各式各樣的炫酷效果,正如一句話:沒有做不到,只有想不到。

iOS流布局UICollectionView系列四——自訂FlowLayout進行瀑布流布局

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.