【问题标题】:Label in UICollectionViewCell not updatingUICollectionViewCell 中的标签未更新
【发布时间】:2016-04-21 01:50:49
【问题描述】:

在我的应用程序中,我正在显示一个日历,并且我正在使用一个集合视图来显示一周中各天的标签。出于某种原因,当我运行应用程序时,所有标签仍显示默认的“标签”。我看了一个类似的问题,但没有帮助。有什么建议么?这是 UICollectionViewCell 的代码:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CalendarTitleCellIdentifier forIndexPath:indexPath];
    UILabel *label = (UILabel *)[cell viewWithTag:1];
    label = [[UILabel alloc] init];
    CGSize size = [self collectionView:collectionView layout:collectionView.collectionViewLayout sizeForItemAtIndexPath:indexPath];
    label.frame = CGRectMake(0, 0, size.width, size.height);
    NSString *title = [[NSString alloc] initWithFormat:@"%@",self.weektitles[indexPath.row]];
    label.text = title;
    NSLog(@"%@", label.text);
    return cell;
}

仅供参考,我在情节提要中有一个实际标签(在集合视图单元格中)。

【问题讨论】:

  • 试试 UILabel *label = (UILabel *)[cell. contentView viewWithTag:1];

标签: ios objective-c uicollectionview uilabel


【解决方案1】:

因为你创建了一个新的 UILabel 点标签。所以你修改 label.text 而不是单元格 label.text。

删除

label = [[UILabel alloc] init]

【讨论】:

    【解决方案2】:
    1. 创建一个 UICollectionViewCell 命名它,例如带有属性的 DayCell

      @property (weak, nonatomic) IBOutlet UILabel *lblName;

    2. 在情节提要中将单元格类从 UICollectionViewCell 更改为 DayCell 并将 Identifier 设置为“daycell”现在将标签 lblName 绑定到情节提要中的标签

    3. 并设置cellForItemAtIndexPath方法

      - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
      static NSString *identifier = @"daycell";
      
      DayCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
      
      
        [cell.lblName setText:@"XYZ"];
      
      
      return cell;
      }
      

    确保您已正确设置集合视图的委托和数据源。

    【讨论】:

      【解决方案3】:

      两行代码都返回一个UILabel

      UILabel *label = (UILabel *)[cell viewWithTag:1];
      label = [[UILabel alloc] init];
      

      后者重新创建了一个标签,它不再属于UICollectionViewCell

      【讨论】:

      • @NickLH,你似乎在最后一行的标签之后删除了一个`,这对这篇文章的内容产生了负面影响
      • 它似乎出现在您的编辑中,因为我只将“line”更改为“lines”,但我现在修复了它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2021-06-25
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多