【问题标题】:Why is titleForHeaderInSection method called multiple times?为什么多次调用 titleForHeaderInSection 方法?
【发布时间】:2014-12-29 12:58:15
【问题描述】:

我有一个简单的项目,它有一个视图,这个视图里面只包含一个表视图。表格视图被分组并且有一个简单的原型单元格。

我已经实现了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 方法被多次调用。

【问题讨论】:

  • 你设置了节数吗?

标签: ios uitableview


【解决方案1】:

UITableView 的委托方法可以在应用执行期间随时调用,任何人都不应完全依赖于它们被调用的次数。大量外部事件会强制 UITableView 重新加载其数据,因此在依赖此函数调用时必须非常小心。

【讨论】:

    【解决方案2】:

    即使节数默认为 1,我也会尝试将其显式设置为 1:

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

    实际上,如果没有这个,它也应该可以工作,但可能有一个错误或类似的东西迫使表格视图产生更多的部分。

    这有帮助吗?

    【讨论】:

    • 嗯嗯好的。尝试检查确切的堆栈跟踪。我唯一想到的是这样的:由于您更改了部分的标题,因此大小也会发生变化,这会在最后触发新的函数调用。可能与此issue 相似
    猜你喜欢
    • 2010-11-11
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2018-12-24
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多