无法在UITableView实现中调用委托/数据源方法
我为UITableView
创build了名为mainTableViewgm.h
和mainTableViewgm.m
.h和.m文件。 我从我的主视图控制器调用 – initWithFrame
:方法到这个mainTableViewgm.m
实现文件
[[mainTableViewgm alloc]initWithFrame:tableViewOne.frame]
请注意,这个tableview是在我的主视图控制器。 但是我已经为tableView创build了单独的文件,并且还在故事板中将自定义类设置为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对象(可能是一种types,你把它们设置在视图控制器上)。 它应该是这样的:
- (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];
没有返回一个有效的单元格对象。 你至less应该使用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
,则委托和数据源的圆圈为空。
解决scheme是按住CTRL键,然后从这些圆圈拖动到包含UITableView
UIView
的名称:
这样做后,我的UITableView
愉快地填充自己。
(所以,我们现在是XCode的6.1版本了吗?你认为苹果会做出这个事情,你知道, 友好的 …?我很想在我的代码中添加一个书签…是一个很好的function。)