1

如何通过 indexPathsForVisibleRows 读取 NSIndexpaths 数组的 intValue?

顺便说一句,为什么 visibleCells 和 indexPathsForVisibleRows 在 if (cell == nil) 函数之前不起作用?

这是我的代码:

在 cellForRowAtIndexPath 方法中:

    static NSString *identifierString;
    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:identifierString];

    // when I use visibleCells and indexPathsForVisibleRows here, the app crashes

    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifierString] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;          
    }

    // when I use visibleCells and indexPathsForVisibleRows here, the app works

//cell implementation here

    return cell;
4

1 回答 1

4

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath是表格视图填充单元格的地方。如果您尝试在创建可见单元格之前引用它们(这是在 if 语句中完成的),则应用程序会崩溃。该alloc命令为要创建的单元分配内存,然后使用某些参数对其进行初始化。此方法被调用的次数与您在 中指定的次数一样多numberOfRowsInSection

这样您就不会一次又一次地重新创建所有单元格,if 语句会检查该单元格是否确实存在,并且仅当它为 nil 时才会创建一个新的单元格来代替。

要获取intIndexPath 的行值,您可以使用它的 row 属性。例如:

NSArray indexArray = [self.tableView indexPathsForVisibleRows];
int i=0;
while(i!=indexArray.count){
   //Log out the int value for the row
   NSLog(@"%d", indexArray[i].row);
   i++;
}

希望这可以帮助

于 2012-07-16T13:24:25.180 回答