我可以强制uitableview中的单元格不是从每个部分的索引0开始吗?

时间:2013-09-07 09:21:39

标签: ios objective-c uitableview

我有一个带有6个单元格和6个分隔符的静态表视图。我需要单元格1的索引为0,单元格6的索引为5,这可能吗?我的下面的代码不起作用,因为每个单元格都在一个单独的部分中,因此它认为每次都选择单元格0,并且它再次使用相同的数据填充单元格,它认为它的单元格为0。

-(void) longTap:(UILongPressGestureRecognizer *)gestureRecognizer
{
    NSLog(@"gestureRecognizer= %@",gestureRecognizer);
    if ([gestureRecognizer state] == UIGestureRecognizerStateEnded)
    {
        NSLog(@"longTap began");

        CGPoint p = [gestureRecognizer locationInView:self.tableView];

        NSIndexPath *indexPath = [myTable indexPathForRowAtPoint:p];
        if (indexPath == nil)
        {
            NSLog(@"long press on table view but not on a row");
        }
        else
        {
            NSLog(@"long press on table view at row %d", indexPath.row);

            switch (indexPath.row)
            {
                case 0:
                    del.tableRowNumber = 0;
                    break;
                case 1:
                    del.tableRowNumber = 1;
                    break;
                case 2:
                    del.tableRowNumber = 2;
                    break;
                case 3:
                    del.tableRowNumber = 3;
                    break;
                case 4:
                    del.tableRowNumber = 4;
                    break;
                case 5:
                    del.tableRowNumber = 5;
                    break;
            }
        }

        UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"MealPlannerRecipeTypeViewController"];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

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

    RecipeInfo *recipeInfo = recipeInfoArray[indexPath.row];
    cell.textLabel.text = recipeInfo.name;
    return cell;
}

我刚试过这个来获取标签:

CGPoint p = [gestureRecognizer locationInView:myTable];
        NSIndexPath *indexPath = [myTable indexPathForRowAtPoint:p];
        UITableViewCell *cell = [myTable cellForRowAtIndexPath:indexPath];

        NSLog(@"TAG IS : %i", cell.tag);

虽然我的表格中仍然使用第一个单元格的值标记了每个单元格?

1 个答案:

答案 0 :(得分:1)

通常,为了实现“直接”计算(即,当部分n+1中的单元格的编号从第n部分的单元格后继续),您需要添加总行数在前面所有部分中的当前行号。

如果您知道每个部分的行数是1,您可以使用“直线”编号的快捷方式,并使用部分编号而不是行编号:

RecipeInfo *recipeInfo = recipeInfoArray[indexPath.section];

每个部分一行的确切公式为indexPath.section * 1 + indexPath.row,但indexPath.row始终为零,我们可以将乘法减少1.您还应该使用

del.tableRowNumber=indexPath.section;

替换长按处理程序中的switch语句。