未设置 CustomTableViewCell 属性(它们为零)

CustomTableViewCell Properties aren't being set (they are nil)

我有一个 customTableViewCell,我正在尝试在上面设置图像和一些文本。单元格创建成功,但属性为nil。我不确定 .xib 中是否遗漏了什么,但我就是想不通。插座设置在customViewCell.h,连接在.xib

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  static NSString *cellIdentifier = @"socialMediaCell";    

  CustomSocialMediaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  CustomSocialMediaTableViewCell *tagCell = (CustomSocialMediaTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"socialMediaCell"];

  if (cell == nil) {

      cell = [[CustomSocialMediaTableViewCell alloc] 
        initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

      tagCell = [[CustomSocialMediaTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  }

  NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"socialPosts"];

  UIImage* image = [UIImage imageWithData:imageData];

  cell.socialMediaTextView.text = @"TEXT";

  cell.socialMediaImageView.image = image;

  return cell;
}

使用以下代码在 if (cell==nil) 中编辑

    if (cell == nil) { //Check cell is nil or not


   NSArray *nib;
   nib = [[NSBundle mainBundle] loadNibNamed:@"CustomSocialMediaTableViewCell"
                                                owner:self options:nil]; //if cell is nil add CustomSocialMediaTableViewCell Xib

   for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomSocialMediaTableViewCell class]])
                cell = (CustomSocialMediaTableViewCell *)oneObject;

    }

您引用同一个 CustomTableViewCell 两次,然后向其分配内容:

static NSString *cellIdentifier = @"socialMediaCell";    

****Declared once here****
CustomSocialMediaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

****Declared a second time here***
CustomSocialMediaTableViewCell *tagCell = (CustomSocialMediaTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"socialMediaCell"];

使用声明的第一个 cell 并删除第二个。

那么你说的是如果单元格为空,请设置样式,你已经做了两次。做一次。

if (cell == nil) {

  cell = [[CustomSocialMediaTableViewCell alloc] 
    initWithStyle:UITableViewCellStyleDefault];
}

然后您可以添加和分配您需要的东西。

我觉得您可能已经尝试通过现代方法以更困难的方式完成此操作,方法是为其创建一个 .xib,而您只需 select 情节提要中的 TableViewCell 并将其设置为 class。然后你可以 ctrl + 从你的 UILabel 和 UIImage 拖到你的 .h 文件。

如果您不想这样做或没有以这种方式构建它,请确保您引用的 UILabel 和 UIImage 已正确连接并且您已声明 IBOutlet 对于两者 - 就像这样

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