UITableview,动态部分&行

时间:2013-07-20 18:36:19

标签: ios uitableview nsmutablearray

想要在一个部分中动态创建一个uitableview

我写这段代码,但我有问题,重复所有部分只有2个第一行

现在我有这一行0,1 - >第0节,第0,1行 - >第1节,第0,1行 - >第2节

想要读取所有行,例如行0,1 - >第0节,第2,3行 - >第1节,第4,5行 - >第2节 - >第6,7行          items = [[NSMutableArray alloc] init];

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    { return items.count/2; }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    { return 2; }   

 - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    UILabel *label = nil;

    cell = [tv dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease];
        label = [[UILabel alloc] initWithFrame:CGRectZero];
        [label setLineBreakMode:UILineBreakModeWordWrap];
        [label setMinimumFontSize:FONT_SIZE];
        [label setNumberOfLines:0];
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];

        [label setTag:1];

        label.textColor = [UIColor darkGrayColor];

        [label setAlpha:0.8];

        cell.backgroundColor = [UIColor whiteColor];

        [[cell contentView] addSubview:label];

    }
    NSString *text = [items objectAtIndex:[indexPath row]];

    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

    if (!label)
        label = (UILabel*)[cell viewWithTag:1];

    [label setText:text];
    [label setFrame:CGRectMake(CELL_CONTENT_MARGIN-5, CELL_CONTENT_MARGIN+30, CELL_CONTENT_WIDTH - ((CELL_CONTENT_MARGIN * 2)+6), MAX(size.height, 44.0f))];

    label.backgroundColor = [UIColor clearColor];

     cell.selectionStyle = UITableViewCellSelectionStyleNone;

    for (UIView *theSubview in [cell.contentView subviews])
    {
        if([theSubview isKindOfClass:[UIImageView class]])
        {
            [theSubview removeFromSuperview];
        }
    }

    UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(128,5, 32, 32)];
    imv.image=[UIImage imageNamed:@"0England.png"];
    [cell.contentView addSubview:imv];
    [imv release];

     if (indexPath.row % 2==0) {

        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(-7 ,10, 8, 18)];
        img.image=[UIImage imageNamed:@"...."];

        [cell.contentView addSubview:img];
        [img release];

    }
    else {  }

     return cell;
}

1 个答案:

答案 0 :(得分:0)

将indexPaths映射到数据结构的行(在本例中为items数组)时出现问题。每个部分的编号从0到ceil(n / 2)(顺便说一句,应该是部分的数量,而不仅仅是n / 2),其中n是items中元素的数量。

该部分内的每一行都有indexPath.row 0或1。

因此,为了从indexPaths映射回items数组,您必须在cellForRowAtIndexPath函数中执行以下操作:

NSString *text = [items objectAtIndex:([indexPath section]*2 + [indexPath row])];