简体   繁体   English

根据数据更改UICollectionViewCell内容和笔尖布局

[英]Change UICollectionViewCell content and nib layout based on data

I have a UICollectionView that is displaying many UICollectionViewCells that I have subclassed as CardCell. 我有一个UICollectionView,它显示许多子类化为CardCell的UICollectionViewCells。 I pass the variable "type" to the CardCell in - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath I want the CardCell class to be able to load a different Nib file depending on what type is passed in. The different types need to have different layouts. 我将变量“类型”传递给CardCell- - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath我希望CardCell类能够根据传递的类型来加载其他Nib文件输入。不同的类型需要具有不同的布局。

The problem is I cannot figure out where to change this in my CardCell.m. 问题是我无法在CardCell.m中找出要更改的位置。 I tried using - (void)prepareForReuse but that does not call unless the user is scrolling. 我尝试使用- (void)prepareForReuse但是除非用户滚动,否则不会调用。

You should register each nib file you need in viewDidLoad, something like this (substituting the correct names for the nib file and the identifier): 您应该在viewDidLoad中注册所需的每个nib文件,如下所示(用正确的名称替换nib文件和标识符):

[self.collectionView registerNib:[UINib nibWithNibName:@"RDCell" bundle:nil] forCellWithReuseIdentifier:@"FirstType"];

Then, in itemForRowAtIndexPath, test for type and return the correct type of cell: 然后,在itemForRowAtIndexPath中,测试类型并返回正确的单元格类型:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        if (type = @"firstType") {
            FirstCell *cell = (FirstCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"FirstType" forIndexPath:indexPath];
            return cell;
        }else{
            SecondCell *cell = (SecondCell *) [collectionView dequeueReusableCellWithReuseIdentifier:@"SecondType" forIndexPath:indexPath];
            cell.whatever .....
            return cell;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM