为什么多次调用titleForHeaderInSection方法?

时间:2014-12-29 12:58:15

标签: ios uitableview

我有一个包含视图的简单项目,此视图内部只包含一个表视图。表视图已分组,并具有一个简单的原型单元格。

我已经实现了titleForHeaderInSection方法来自定义节标题。当我查看调试输出时,我看到该应用程序多次在titleForHeaderInSection打印日志语句。有时两次,有时三次。有谁知道为什么?

这是我的代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *initialTitle = @"A title";
    NSLog(@"titleForHeaderInSection: %@", initialTitle);
    return initialTitle;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *myLabel = [UILabel new];
    myLabel.frame = CGRectMake(20, 20, 320, 20);
    myLabel.font = [UIFont boldSystemFontOfSize:20];
    myLabel.text = @"Test";
    UIView *headerView = [UIView new];
    [headerView addSubview:myLabel];
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath];
    return cell;
}

@end

这是调试输出:

2014-12-29 14:57:30.806 TestTitleForHeaderInSection[5212:118874] titleForHeaderInSection: A title
2014-12-29 14:57:30.812 TestTitleForHeaderInSection[5212:118874] titleForHeaderInSection: A title
2014-12-29 14:57:30.812 TestTitleForHeaderInSection[5212:118874] titleForHeaderInSection: A title

我还注意到多次调用numberOfRowsInSection方法。

2 个答案:

答案 0 :(得分:0)

尽管默认情况下部分的数量是1,但我会尝试将其明确地设置为1:

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

实际上它也可以在没有这个的情况下工作,但也许有一个bug或类似的东西迫使Table View产生更多的部分。

这有帮助吗?

答案 1 :(得分:0)

UITableView的委托方法可以在程序执行的任何时候调用,没有人应该根据它们被调用的次数来计算。大量外部事件可以强制UITableView重新加载其数据。所以当你依赖这个函数调用时你必须非常小心。

相关问题