Как мне добавить счетчик в ячейку в ячейках UICollectionView?

#ios #ios7 #uicollectionview #uicollectionviewcell

#iOS #ios7 #uicollectionview #uicollectionviewcell

Вопрос:

У меня есть следующий код:

 - (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];

    return cell;
}
 

Как мне добавить счетчик в dispaly в моей ячейке, который показывает номер ячейки в порядке ее создания? Например, в ячейке 1 будет указано 1, 2 равно 2 и так далее.

Ответ №1:

Создайте подкласс UICollectionViewCell . Добавьте счетчик (может быть, просто метку?) В метод инициализации ячейки. Зарегистрируйте свой класс для идентификатора ячейки по вашему желанию

 [self.collectionView registerClass:[MyCollectionViewCell class] 
        forCellWithReuseIdentifier:@"myCellIdentifier"];
 

и удалите ячейку из очереди с идентификатором. Затем установите значение метки.

 - (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor whiteColor];
    cell.counterLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];

    return cell;
}