UICollectionView and access UICollectionViewCell



我如下创建自定义的UICollectionViewCell

  1. 转到文件->新建->文件->用户界面->清空->调用此nib"customNib"
  2. 在customNib中,在.中拖动UICollectionViewCell

    赋予其重用小区标识符@"Cell"

    细胞内,UILabel is inserted to label the cell

  3. File -> New -> File -> Cocoa Touch Class -> Class named "CustomCollectionViewCell" subclass of UICollectionViewCell.

  4. 返回自定义笔尖,单击单元格并创建指向此自定义的链接类别CCD_ 6。

    插入UILabel的出口作为CCD_ 8在CCD_。

所以CustomCollectionViewCell.h类有

#import <UIKit/UIKit.h>
@interface CustomCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *cellText;

@end
  1. 转到ViewController的viewDidLoad并插入

代码:

UINib *nib = [UINib nibWithNibName:@"customNib" bundle:nil];
 [_collectionView registerNib:nib forCellWithReuseIdentifier:@"Cell"];
  1. 然后在

代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
   //here i need to access cell's UILabel to write text    
}

在步骤6,我需要使用插入的UILabel来标记小区。如何访问小区内的UILabel

通过替换将退出队列的单元格转换为自定义类

UICollectionViewCell *cell = 
    [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" 
                                              forIndexPath:indexPath]; 

带有:

CustomCell *cell = 
    (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" 
                                                            forIndexPath:indexPath];

然后你应该能够访问你的标签。

最新更新