如何在UICollectionViewCell中设置UILabel

mar*_*oko 3 ios uicollectionviewcell

我有一个带有UIViewController的应用程序,里面有一个UICollectionView IBOutlet.

MyCustomCell Outlet已连接 MyCustomCell ReuseID MyCustomCell类标识

UICollectionView中的单元格是MyCustomCell,并且此方法设置其UILabel:

-(void)setCellLabel:(NSString *)value{
    NSLog(@"settinglabel");
    cellLabel.text = @"hardcode"; //added for testing purposes
}
Run Code Online (Sandbox Code Playgroud)

单元格具有属性类型类型,在故事板中将其标识为MyCustomCell,以及它的出列标识符.UIViewController采用数据源和委托协议.IBOutlet UILabel的cellBabel插座连接到故事板.方法定义为:

- (void)viewDidLoad{
    [super viewDidLoad];
    self.restNames = @[@"Orange",@"Naranja",@"Narnia"];

    [self.collectionView registerClass:[MyCustomCell class] forCellWithReuseIdentifier:@"MyCustomCellID"];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSLog(@"%d",[self.restNames count]);
    return [self.restNames count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];


    [cell setCellLabel:@"hi"];
    NSLog(@"fitsname %@",[self.restNames objectAtIndex:indexPath.row]);


    return cell;
}
Run Code Online (Sandbox Code Playgroud)

我在tableview中绘制了三个单元格,对应于我的数组中的3个对象.该数组只包含我直接由objectAtIndexPath设置的字符串对象,但我决定将它直接设置为@"hi",因为它不起作用.我甚至将setCellLabel方法中使用的值更改为硬编码值,并且每个单元格中只保留"Label"默认字符串.

为什么cellLabel没有正确设置?

Pat*_*her 5

您是否在界面构建器中设置了cellLabel插座?

你应该在你的单元格的.h文件中有这样的东西:

@property (weak, nonatomic) IBOutlet UILabel *cellLabel;
Run Code Online (Sandbox Code Playgroud)

然后你真的需要这样做:

cell.cellLabel.text = @"";
Run Code Online (Sandbox Code Playgroud)

  • 您是否再次调用[self.collectionView registerClass:[MyCustomCell class] forCellWithReuseIdentifier:CellIdentifier]?如果您使用的是故事板,则不希望将其称为"故事板".它将覆盖故事板中的内容. (13认同)

dul*_*gan 5

当您使用Storyboard时,默认模板是错误的,因为它使用了该行

[self.collectionView registerClass:[UICollectionView class] forCellWithReuseIdentifier:CellIdentifier];
Run Code Online (Sandbox Code Playgroud)

故事板已经注册了它.所以基本上这就是你要创建自定义故事板的基础UICollectionView:

  1. 创建UICollectionViewController子类
  2. 单击并拖动UICollectionViewController到故事板并根据需要更改配置
  3. 创建一个UICollectionViewCell子类
  4. 在故事板中设置单元格类,设置它的重用标识符ctrl-拖动所需的出口
  5. 除掉 [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier: CellIdentifier];
  6. UICollectionView子类中设置静态重用标识符