[英]iOS 7 UITableView indexpath row property is nil
我有一个UITableView
,它包含一个自定义UITableViewCell
。 为了测试,我有一个包含三个字符串的数组。 UITableView
委托方法按预期调用,但是, tableView:cellForRowAtIndexPath委托总是传递一个NSIndexPath
实例,其行属性始终为== nil
:
tableView:cellForRowAtIndexPath
被调用3次(对于我的数组中的每个对象一次)。 我在设计器(故事板)中添加了tableView
,并为它创建了一个插座。 UITableViewCell实例似乎已正确实例化,每次调用此委托。 我无法[indexPath row]
为什么[indexPath row]
值始终为nil
。
接口(一个或多个):
在implmentation文件中:
@interface FirstViewController ()
@property(nonatomic, strong)AppDelegate *sharedDelegate;
@property(nonatomic, strong)NSArray *userList;
@end
在标题中:
@interface FirstViewController : UITableViewController <FacebookDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end
初始化自定义单元格:
-(void)viewDidLoad
{
[self.tableView registerClass: [ListCategoryCell class]forCellReuseIdentifier:@"ListCategoryCell"];
self.userList = @[@"d", @"g", @"f"]; // make some test data
}
代表这让我很生气:
//NSIndexPath.row is nil ?!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"ListCategoryCell";
ListCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = (ListCategoryCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier];
}
cell.titleLabel.text = [self.userList objectAtIndex:[indexPath row]];
cell.detailLabel.text = @"Detail";
return cell;
}
我错过了什么吗? 谢谢!
现在工作
我遗漏了一些我认为与我的问题非常相关的背景(我不应该)。 我最初创建了一个UIViewController,然后在其中添加了一个UITableView作为视图。 在UITableView中,我创建了一个自定义原型单元格。 我做了所有的家务:
UIViewController
实现了UITableViewDelegate
和UITableViewDatasource
。 为UITableView
创建和插座。 连接所有的网点
除了indextPath.row
属性总是nil
之外,一切似乎都有效。 我发现的一些资源表明,在调用uitableview委托之前,自定义单元格是不可见的。
最后,我使我的类成为UITableViewController
的子类。 事情开始奏效了。 我仍然很好奇为什么我最初的尝试失败了。
谢谢大家的时间。 一些好的评论帮助我调查了一些“很有价值”的主题。
如果要管理表视图,则需要在视图控制器中至少提供两种方法。 他们是:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
你已经提供了第二个,所以你的表视图实际上可以产生单元格,但它不知道多少。第一个方法返回的默认值是nil。这就是你甚至没有索引路径的原因。
可选:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
默认值为1,因此如果只有一个部分,则无需重写此值
确保您的视图控制器也遵循委托和数据源协议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.