从代码加载UITableViewController

时间:2012-04-02 13:37:35

标签: iphone objective-c xcode uiviewcontroller

我遇到的问题是我只能想象一个非常简单的问题。我正在从一个UITableViewController加载一个名为LocationViewController的{​​{1}}课程:

UIViewController

在本课程中,我实现了以下3种方法:

LocationViewController *lvc = [[LocationViewController alloc] init];
[self.navigationController pushViewController:lvc animated:true];

我收到以下错误:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

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

我在使用StoryBoard在ViewControllers之间转换之前遇到此错误,这是因为CellIdentifier不正确。我不知道我做错了什么。我试过用这个ViewController加载一个nib文件,但是会抛出同样的错误。

4 个答案:

答案 0 :(得分:3)

您必须分配单元格。使用此代码。

static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

答案 1 :(得分:0)

使用此代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = @"Test";
return cell;}

答案 2 :(得分:0)

如果可重用单元队列中没有对象,则

dequeueReusableCellWithIdentifier返回nil。在调用dequeueReusableCellWithIdentifier后检查cell是否为nil,在这种情况下创建一个新的UITableViewCell。

答案 3 :(得分:0)

dequeueReusableCellWithIdentifier是已创建的UITableViewCells的缓存,其标识符为“CityCell”

如果您使用下面的代码,它会尝试从缓存中获取一个单元格,如果不能,则会创建一个单元格,然后将其存储在单元格缓存中供以后使用。

您需要大型表的缓存,因为它在滚动时大大提高了表的性能。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"CityCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    }
    cell.textLabel.text = @"Test";

    return cell;
}

查看表格视图编程指南以了解更多相关信息:

Table Programming Guide

相关问题