[英]Fails to call delegate/datasource methods in UITableView implementation
我为UITableView
创建了.h和.m文件,分别称为mainTableViewgm.h
和mainTableViewgm.m
。 和我打电话- initWithFrame
:方法从我的主视图控制器此mainTableViewgm.m
实现文件
[[mainTableViewgm alloc]initWithFrame:tableViewOne.frame]
请注意,此tableview在我的主视图控制器中。 但是我为tableView创建了单独的文件,并且还在故事板上将自定义类设置为mainTableViewgm
。
-initWithFrame:
方法如下所示
- (id)initWithFrame:(CGRect)frame
{
//NSLog(@"kource data");
self = [super initWithFrame:frame];
if (self)
{
[self setDelegate:self];
[self setDataSource:self];
[self tableView:self cellForRowAtIndexPath:0];
[self tableView:self numberOfRowsInSection:1];
// Initialization code
}
return self;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(@"kource data");
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"kource data2");
UITableViewCell*cellOne =[[UITableViewCell alloc]init];
cellOne.detailTextLabel.text=@"text did appear";
return cellOne;
}
-initWithFrame:
在此方法中与“ if(self)”块一起被很好地调用。 但是问题是numberOfRowsInSection:
和cellForRowAtIndexPath:
没有在这里自动调用。 kource data
/ kource data2
永远不会出现在日志中。 我要如何装载桌子? delegate
/ datasource
设置不正确吗?
我必须提到,我还设置了UITableViewDelegate
和UITableviewDataSource
协议:
@interface mainTableViewgm : UITableView <UITableViewDelegate,UITableViewDataSource>
@end
帮助将不胜感激。 谢谢。
控制器初始化时不会加载tableview,因此您不能在init
方法中这样做。 您必须将代码移至viewDidLoad
方法。
另外,您没有在tableview对象上设置委托和数据源(可能是类型,而是在视图控制器上设置它们)。 它看起来应该像这样:
- (void)viewDidLoad:(BOOL)animated {
[super viewDidLoad:animated];
[self.tableView setDelegate:self];
[self.tableView setDataSource:self]; // <- This will trigger the tableview to (re)load it's data
}
下一步是正确实现UITableViewDataSource方法。 UITableViewCell *cellOne =[[UITableViewCell alloc] init];
没有返回有效的单元格对象。 您至少应使用initWithStyle:
看看如何使用dequeueReusableCellWithIdentifier:forIndexPath:
典型的实现如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
// Reuse/create cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Update cell contents
cell.textLabel.text = @"Your text here";
cell.detailTextLabel.text=@"text did appear";
return cell;
}
我不敢相信我从事XCode编程已经两年了,仍然遇到了这个问题。
我在XCode 6.1中遇到了同样的问题-我在viewWillAppear
函数中设置了UITableView
的委托和数据源,但是没有一个委托函数在起作用。
但是,如果右键单击情节提要上的UITableView
,则代表和dataSource的圆圈为空。
然后,解决方案是按住CTRL键,并从每个圆圈中拖动到包含UITableView
UIView
的名称:
完成此操作后,我的UITableView
愉快地填充自身。
(所以,现在我们的XCode达到v6.1了吗?您认为Apple会做到这一点吗,您知道吗, 友好的吗??我想在我的代码中添加一个书签...会是一个不错的功能。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.