[英]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.