-1

我想设计一个有 2 个部分的动态表,第一个部分有 4 个单元格,第二个有 41 个单元格。我想分别对这两个部分进行编程,但我只能修改一个部分。如何分别修改每个部分。到目前为止我写的代码是这样的:

{
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

        return 2;
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        if (section == 0)
            return 4;
        else
            return 41;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Questions";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Questions"];

        cell.textLabel.text = [NSString stringWithFormat:@"Question %lu", (unsigned long)indexPath.row +1];

        return cell;
    }
}
4

1 回答 1

2

NSIndexPath 有一个 row 属性和一个 section 属性。从这两个属性中,您可以知道您当前正在哪个单元格中工作

  • <(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

例如:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Questions";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Questions"];

        if (indexPath.section == 0)
        {
            cell.textLabel.text = [NSString stringWithFormat:@"1st Group - Question %d", indexPath.row + 1];
        }
        else
        {
            cell.textLabel.text = [NSString stringWithFormat:@"2nd Group - Question %d", indexPath.row + 1];
        }

        return cell;
    }
于 2012-08-04T07:17:56.507 回答