在iOS 6中填充Tableview单元格

时间:2012-10-25 07:00:33

标签: objective-c uitableview

我尝试过搜索一些关于如何填充表格视图的教程,但我发现的所有内容都是陈旧过时的视频。我尝试从稍微更新的那个做,但它不起作用。我有

- (void)viewDidLoad
{
    [super viewDidLoad];
   [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [chemarray addObject:@"2"];
    [chemarray addObject:@"test"];
    [chemarray addObject:@"3"];
    [chemarray addObject:@"science"];  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [chemarray count];
}

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"     forIndexPath:indexPath];

     cell.textLabel.text = [chemarray objectAtIndex:indexPath.row];
    return cell;
}

根据本教程,运行时,它应该显示我的数组中的项目,但对我来说,它不会!有谁知道如何解决这个问题?

4 个答案:

答案 0 :(得分:24)

您忘记了register nib / class作为单元格标识符。

形成Apple UITableView文档:

  

重要说明:您必须使用以下命令注册类或nib文件   registerNib:forCellReuseIdentifier:或   在调用dequeueReusableCellWithIdentifier:forIndexPath:之前registerClass:forCellReuseIdentifier:方法   方法

以下是普通UITableViewCell的示例:

- (void) viewDidLoad {
   [super viewDidLoad];

   [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

如果您未注册nib / class,则方法dequeueReusableCellWithIdentifier:forIndexPath:dequeueReusableCellWithIdentifier:基本相同。并且它不会自动为您创建实例。

答案 1 :(得分:3)

我遇到了同样的问题。如果您使用的是iOS6,那么我假设您使用的是故事板,并且您将视图控制器与自定义类相关联。

然后解决方案是进入故事板,转到tableview中单元格的属性,并将Identifier值更改为“Cell”。无需在ViewDidLoad中注册该类。

答案 2 :(得分:1)

  1. 将代理设置为uitableview.delegate = self;
  2. 检查您是否有声明协议<UITableViewDelegate, UITableViewDataSource>
  3. 如果您不使用故事板,请确保如果单元格== nil ,则为init单元格

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
     if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
     }
    

答案 3 :(得分:1)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.textLabel.text = [chemarray objectAtIndex:indexPath.row];
    return cell;
}

确保UITableViewDataSource中有UITableViewDelegate.h,并tableview代表,数据源和cellindentifier单元格与.xib相关联