测试 UITableView 的节页脚



尝试在UITableView中创建的UITableView中测试UISegmentedControl:

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        UIView *container = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, [self tableView:tableView heightForFooterInSection:section])];
        [self.segmentedControl setCenter:container.center];
        [container addSubview:self.segmentedControl];
        return container;
    } else {
        return [super tableView:tableView viewForFooterInSection:section];
    }
}

在测试类中:

-(void)testSegmentedControl {
    MyTableViewController *viewController = [[MyTableViewController alloc]initWithNibName:@"MyTableViewController" bundle:nil];
    [viewController.tableView reloadData];
    // Getting the footer via the delegate is cheating IMO.
    UITableViewHeaderFooterView *footer =  [viewController.tableView footerViewForSection:0];
    UISegmentedControl *segmentControl = footer.subviews[0];
    // do stuff to the segmentControl then check the tableView.
    [viewController.tableView reloadData];
}

我目前正在通过全局属性(viewController.segmentedControl)操作UISegmentedControl,然后调用[viewController.tableView reloadData]来更新UITableViewCell的状态。但在我看来,从[viewController.tableView footerViewForSection:0]获取页脚是正确的测试方法。任何指导都值得赞赏。

编辑:

正如John Rodgers所建议的那样,我尝试像cellForRowAtIndexPath:一样将UITableViewHeaderFooterView排入队列

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        UITableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerReuseId];
        if (footer == nil) {
            footer = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:self.footerReuseId];
        }
        if (![footer.subviews containsObject:self.segmentedControl]) {
            [footer addSubview:self.segmentedControl];
        }
        return footer;
    } else {
        return [super tableView:tableView viewForFooterInSection:section];
    }
}

测试方法没有改进:

-(void)testSegmentedControl {
    MyTableViewController *viewController = [[MyTableViewController alloc]initWithNibName:@"MyTableViewController" bundle:nil];
    [viewController.tableView reloadData];
    UITableViewHeaderFooterView *footer1 = (UITableViewHeaderFooterView *)[viewController.tableView dequeueReusableHeaderFooterViewWithIdentifier:viewController.footerReuseId];
    UITableViewHeaderFooterView *footer2 = [viewController.tableView footerViewForSection:0];
    // Break point shows that footer1 and footer2 are nil.
}

您在这里遇到的问题是,footerViewForSection实际上是一个 UITableView 方法,用于为其提供该部分的视图。

您必须将可重用的UITableViewHeaderFooterView取消排队,以便在测试类中对其进行测试:

UITableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:mySectionFooterViewIdentifier];

这正是您应该在为表视图提供footerViewForSection方法中使用的方法,您只需在测试类中将其取消排队即可。

希望这有帮助!

~ J

最新更新