2017-04-05 83 views
-1

我在Storyboard中添加了一個TableViewController,並將其類型更改爲繼承UITableViewController的自定義類。 我還在故事板中添加了一些單元格。 (不是自定義的,基本的UITableViewCells) 現在我想以編程方式修改這些單元格(如有條件地添加披露指示符)。所以,我做了我的班採取的UITableViewDelegate,但是當我嘗試以編程方式修改我的單元格的文本,我得到這個錯誤:無法從其dataSource中獲取單元格 - 故事板和代碼

NSInternalInconsistencyException : failed to obtain a cell from its dataSource

下面是代碼:

@interface MyTableViewController() <UITableViewDelegate> 
@end 

@implementation MyTableViewController 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    cell.textLabel.text = @"test"; 
    return cell; 
} 

@end 

在我的故事板,在引用出口,我正確地有dataSource和委託鏈接到表視圖。 我在這裏錯過了什麼?感謝您的幫助

+0

您正在調用'[tableView cellForRowAtIndexPath:indexPath]'?這不是要調用的方法。調用'UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@「someCellID」forIndexPath:indexPath];' – Larme

+0

對於您的表格視圖內容,您使用的是動態原型還是靜態單元格? –

+0

@Larme謝謝你的回覆。我嘗試在我的故事板中設置標識符「TestCell」,並用'dequeueReusableCellWithIdentifier'替換了'cellForRowAtIndexPath',但現在我得到這個錯誤:'無法使標識符TestCell出隊 - 必須爲標識符註冊一個筆尖或類,連接故事板中的原型單元格 – Someday

回答

1

您應該使用-dequeueReusableCellWithIdentifier:代替[tableView cellForRowAtIndexPath:indexPath]; 但首先,如果你使用的是故事板或XIB你必須有設置reuseIdentifier和檢查,如果你使用相同的reuseIdentifier在[tableView dequeueReusableCellWithIdentifier:@"<your cell id>"];,如果你不使用IB你應該[self.tableView registerClass:forCellReuseIdentifier:]

註冊您的細胞,但要注意,有2種不同的方法

1. - (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;

2. - (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;

如果設置未註冊reuseIdentifier在第一個,你會得到一個細胞== nill和第二你會得到的情況下崩潰 ,如果你得到它的零您可以創建和使用註冊新的細胞:

if (cell == nil) 
    { 
     cell = [UITableViewCell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:<your cell id>]; 
    } 
+0

我嘗試了這一點,但即使我在IB中首先設置了我的標識符,我仍然無法使標識符TestCell出錯。應用程序崩潰之前,它檢查單元格== nil,它崩潰的第一行:'UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@「TestCell」forIndexPath:indexPath];' – Someday

+0

@Someday如果你打電話withiout'forIndexPath'的事情,你會沒有崩潰......但仍然存在一個奇怪的行爲,你是否在故事板或單獨的.xib文件中創建單元格? –

+0

如果使用.xib,你必須註冊它:#tableView registerNib:[UINib nibWithNibName:@「」bundle:nil] forCellWithReuseIdentifier:@「」] –

-1
static NSString *simpleTableIdentifier = @"TxtTableViewCell"; 
TxtTableViewCell *cell = (TxtTableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 
if (cell == nil) { 
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"TxtTableViewCell" owner:self options:nil]; 
    cell = [nib objectAtIndex:0]; 
}