在UITableView中,cellForRowAtIndexPath忽略前几行

问题描述:

我已经在我的项目中使用了sqlite,并且我在_mChats(array)中成功获得了10个元素。 numberOfRowsInSection方法返回10,但cellForRowAtIndexPath忽略了前几​​行,并在模拟器中的其他元素都显示在同一个单元格,为什么? 如果我使用部分而不是行来显示数据,一切都变得正常。在UITableView中,cellForRowAtIndexPath忽略前几行

这是我的代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
     return 1; 
    } 
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     return [_mChats count]; 
    } 

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     VChat *cell = [VChat vChatWithTableView:tableView]; 
     cell.mChat = _mChats[indexPath.section]; 
     return cell; 
    } 
+1

为什么你使用'indexPath.section',得到目标对象的指数'cellForRowAtIndexPath'?使用'indexPath.row' – NSNoob

+1

此外,为什么不出院和重用细胞? – NSNoob

我认为它是因为这个 cell.mChat = _mChats[indexPath.section];

试试这个 cell.mChat = _mChats[indexPath.row];

这是因为Indexpath的是,在其内部具有两个值的属性, 例如。 IndexPath [节,行]含义in​​dexpath是节号1,节号5. 希望这可以帮助你理解。

这是怎么了你cellForRowAtIndexPath应该是这样的:

- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath { 
    NSString *cellIdentifier = @"myCell"; 

    UITableViewCell *cell = (UITableViewCell *)[iTableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; 
    } 

    cell.mChat = _mChats[indexPath.row]; 

    return cell; 
} 
+0

+(instancetype)vChatWithTableView:(UITableView *)tableView {0} {0} {0}静态NSString * cellIdentifier = @“cellInChatView”; VChat * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if(!cell)cell = [[VChat alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } return cell; } – rayesquire

- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath 
{ 
    VChat *cell = (VChat *)[tableViewdequeueReusableCellWithIdentifier:@"CellIdentifier"]; 
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"VChat" owner:self options:nil]; 
    if (cell==nil) 
    { 
    cell = nib[0]; 
    } 
    cell.mChat = _mChats[indexPath.row]; 
    return cell; 
} 

三个委托方法必须实现你写的有什么不对。正如@Abhinav所说的方法返回单元有一些错误。

由于您显示的代码将在屏幕中出现新的单元格时创建新的单元格。我认为的前几行只是因为细胞没有被重用。

还有一件事我想说,如果你使用的是故事板打造的tableview这个方法应该看起来像:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    // The identifier in storyboard you setted. 
    static NSString *cellName = @"theCell"; 
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellName]; 
    if (dataSource_[indexPath.row]) { 
     // This method will bind data to view 
     [cell fillDataWithDict:dataSource_[indexPath.row]]; 
    } 
    return cell; 
}