具有多个部分的UITableView仅显示一个部分

时间:2014-03-19 03:17:25

标签: ios objective-c uitableview

我有一个看似非常简单的问题。我的APP中有一个UITableView。在numberOfSectionsInTableView:中,我将节的数量设置为2.但是tableView仅显示第一节。我尝试通过在两个部分中编写相同的代码使这两个部分显示相同的内容,但没用。然后我在这里发现了类似的问题。但它的正确答案是框架,我的布局非常简单UITableViewController。最后我尝试将NSLog添加到这三种方法中。结果是:对于案例部分1,numberOfSectionsInTableView:numberOfRowsInSection:被调用,但cellForRowAtIndex未被调用。我想知道如何解释这个。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    int count;
    switch (section) {
        case 0:
            count = [_objectArray count];
            break;
        case 1:
            NSLog(@"section called");       // This line is logged
            count = 1;
        default:
            count = 0;
            break;
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"myCellIdentifier";
    static NSString *basicCellIdentifier = @"myBasicCellIdentifier";

    switch ([indexPath section]) {
        case 0: {
            TableViewStoryCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
                                                   forIndexPath:indexPath];

            // Configure the cell...
            int theIndex = [indexPath row];
            MyObject *theObj = [_objectArray objectAtIndex:theIndex];
            cell.object = theObj;
            return cell;
            break;
        }
        case 1: {
            NSLog(@"cell called");      //this line isn't logged
            for (int i = 0; i < 50; i++) {
                NSLog(@"hahaha");
            }
            MyBasicViewStoryCell *cell = [tableView dequeueReusableCellWithIdentifier:basicCellIdentifier forIndexPath:indexPath];
            return cell;
            break;
        }
        default: {
            for (int i = 0; i < 50; i++) {
                NSLog(@"hahaha1");
            }
            return nil;
            break;
        }
    }
}

3 个答案:

答案 0 :(得分:2)

break放入开关案例中。您错过了break中的case 1:,因此默认也会执行。因此,计数变为零count = 0。由于numberOfRowsInSection:返回零,cellForRowAtIndexPath:将不会调用。因此,break放在case 1:

numberOfRowsInSection:
switch (section) {
    case 0:
        count = [_objectArray count];
        break;
    case 1:
        NSLog(@"section called");       // This line is logged
        count = 1;
        break;                          // Here
    default:
        count = 0;
        break;
}

答案 1 :(得分:1)

设置第1部分的计数后,你没有休息时间,它会落空并设置为零。

    case 1:
        NSLog(@"section called");       // This line is logged
        count = 1;
        break; // always put break!

答案 2 :(得分:0)

如果numberOfRowsInSection没有返回&gt; = 1的值,则不会调用

cellForRowAtIndexPath。

相关问题