【问题标题】:Add UILabel to a specific indexpath in UICollectionView将 UILabel 添加到 UICollectionView 中的特定索引路径
【发布时间】:2016-11-17 07:43:41
【问题描述】:

这是我的代码

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}

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

    if (indexPath.item == 0) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 50)];
        label.text=[NSString stringWithFormat:@"this is item %ld", (long)indexPath.item];
        [cell.contentView addSubview:label];
        cell.contentView.backgroundColor = [UIColor greenColor];

        NSLog(@"im @ zero");

    } else {
        NSLog(@"im here %ld", (long)indexPath.item);
        cell.contentView.backgroundColor = [UIColor yellowColor];

    }

    return cell;
}

我只想在索引路径零处添加标签。 我遇到了问题,因为标签也出现在其他索引路径中..

【问题讨论】:

    标签: objective-c uilabel uicollectionviewcell


    【解决方案1】:

    在您的情况下,在 if 条件内,您还可以添加:

    label.tag = 1000; // or other number
    

    而且,在 else 里面添加:

    [cell.contentView viewWithTag:1000].hidden = YES;
    

    问题在于 indexPath.item == 0 处的单元格可能会被其他索引路径重用,并且仍然可见。

    希望它有意义。

    【讨论】:

    • @SunilKumar 不客气!它奏效了吗?如果是 - 请接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多