自定义单元格不会出现在tableview中

时间:2013-02-14 07:22:39

标签: ios objective-c xcode uitableview

我使用故事板。我在故事板中为我的Cell创建了一个新类,我在重用标识符“userFullCell”中编写。我的Cell类.h

#import <UIKit/UIKit.h>

@interface UsefullLinksCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *image;
@property (weak, nonatomic) IBOutlet UILabel *shortTitle;

@end

.m默认

#import "UsefullLinksCell.h"

@implementation UsefullLinksCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
  self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  if (self) {
    // Initialization code
}
return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
  [super setSelected:selected animated:animated];

// Configure the view for the selected state
}

属性图像 shortTitle 在故事板中与UILabel和单元格中的UIImageView连接

然后在我的UITableView类中导入“UseFullLinksCell.h”并在viewDidLoad中写道:

[self.tableView registerClass:[UsefullLinksCell class] forCellReuseIdentifier:@"userFullCell"];

tableView是我的出路:

@property (weak, nonatomic) IBOutlet UITableView *tableView;

然后我尝试创建单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"userFullCell";
  UsefullLinksCell *cell = (UsefullLinksCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  NSDictionary *info = resourceArray[indexPath.row];
  if(info){
    cell.image.image = info[@"logo"];
    cell.shortTitle.text = info[@"title"];
  }
  return cell;
}

因此,单元格初始化,但图像和文本未分配,并且在方法结束后返回0x0000000单元格。如果我在这个方法中创建标准的单元格代码,我的意思是UITableViewCell *单元格,这一切都很好。哪里可以弄错? PS对不起,我无法从故事板中截取屏幕截图,因为我不是从我的电脑上写的,如果你愿意,我会在以后提供图片

3 个答案:

答案 0 :(得分:6)

您应该在您创建自定义单元格而不是类的情况下注册xib文件(使用registerNib:forCellReuseIdentifier :)。此外,我不知道这是否会有所作为,但请更换:

UsefullLinksCell *cell = (UsefullLinksCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

使用此方法(注意方法末尾的forIndexPath:):

UsefullLinksCell *cell = (UsefullLinksCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

编辑后:

如果在故事板中向表视图添加了一个自定义单元格,并为其指定了标识符“userFullCell”,那么您无需注册任何内容 - 实际上,注册您的类会使其无效。所以,只需注释掉寄存器语句,看看是否有效。

答案 1 :(得分:1)

你错过了一些东西:

  NSArray *objects=[[NSBundle mainBundle]loadNibNamed:@"UsefullLinksCell" owner:self options:nil];
 UsefullLinksCell *cell =[objects objectAtIndex:0];

这将为您提供自定义单元格的对象。

答案 2 :(得分:0)

我认为您必须执行以下操作

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 {
     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
     if (self) {
      // Initialization code

          image=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,50.0,50.0)];
          shortTitle=[[UILabel alloc] initWithFrame:CGRectMake(60.0,0.0,200.0,50.0)];
     }
     return self;
}

否则一切都应该工作..问题是你的组件没有在任何地方初始化,要么应该从xib加载,要么必须手动初始化它们。

希望这有帮助。

相关问题