2012-04-02 50 views
0

我遇到了问题,我只能想象是一个非常简单的问题。我从一个UIViewController加载UITableViewController类叫做LocationViewController从代码加载UITableViewController

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

在这个类我已经实现以下3个方法:

- (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; 
} 

而且我收到以下错误:

UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:' 

在使用StoryBoard在ViewControllers之间转换之前,我有过这个错误,这是因为CellIdentifier不是c orrect。我不知道我做错了什么。我试过用这个ViewController加载一个nib文件,但是会引发同样的错误。

+0

只是可以肯定...你验证**这**的cellForRowAtIndexPath:实际上是被调用(并可能在返回之前记录'cell'的值)? – 2012-04-02 13:43:00

回答

3

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

static NSString *CellIdentifier = @"Cell"; 

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

感谢您抽出宝贵时间回答问题。 – SamRowley 2012-04-02 13:53:24

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;} 
0

dequeueReusableCellWithIdentifier返回nil,如果在可重复使用的单元的队列中没有对象。在调用dequeueReusableCellWithIdentifier之后检查单元是否为零,在这种情况下创建一个新的UITableViewCell。

0

dequeueReusableCellWithIdentifier与您的标识符“CityCell”

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

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

- (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