具有多个部分时,表视图为黑色

时间:2014-01-07 05:43:29

标签: ios uitableview xcode5

我正在尝试让我的视图控制器中的tableView返回多个部分。但是,每当我这样做并最终将文本放在节标题中时,我会得到一个黑屏,但没有错误。但是,更改为一个部分并且没有在故事板或代码中输入标题文本,将正确显示tableview。有什么我做错了吗?

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return @"Header1";
    }
    else if (section == 1)
    {
        return @"Header2";
    }
    return nil;
}

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    long num = indexPath.row;
    UITableViewCell *cell;
    switch (num)
    {
        case 0:
            cell = self.firstCell;
            break;
        case 1:
            cell = self.secondCell;
            break;
        case 2:
            cell = self.thirdCell;
            break;
        case 3:
            cell = self.fourthCell;
            break;
    }
    return cell;
}

1 个答案:

答案 0 :(得分:2)

您的单元格未初始化,因此请先对其进行初始化。有关详细信息,请参阅此代码。

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      if(indexPath.section == 0)
      {

            static NSString *cellIdentifier = @"Cell";

            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (!cell)
            {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            switch (indexPath.row)
            {
                case 0:
                    cell = self.firstCell;
                    break;
                case 1:
                    cell = self.secondCell;
                    break;
                case 2:
                    cell = self.thirdCell;
                    break;
                case 3:
                    cell = self.fourthCell;
                    break;
            }
            return cell;
}
else
{
        static NSString *cellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        switch (indexPath.row)
        {
            case 0:
                cell = self.firstCell;
                break;
            case 1:
                cell = self.secondCell;
                break;
            case 2:
                cell = self.thirdCell;
                break;
            case 3:
                cell = self.fourthCell;
                break;
        }
        return cell;
     }
}
相关问题