我在stackoverflow上没有找到类似的问题,所以我会发布自己的问题(如果有不理解的地方,请告诉我):
问题:
我在自定义的UITableViewController
中使用带有A-Z部分标题的常规索引tableView
(如contacts.app中的那样)。 我重写了tableView:viewForHeaderInSection:
来提供自己的部分标题视图。
当用户向上或向下滚动表格时,我需要监听出现/消失在tableView顶部或底部的部分标题(以相应地更改某些自定义视图)。
我重写了自从iOS 6.0以来可用的这些方法,它们正好可以做到这一点:
tableView:didEndDisplayingHeaderView:forSection:
tableView:willDisplayHeaderView:forSection:
2. 在向上/向下滚动tableView时从未被调用,而方法1每次部分标题从屏幕消失时都会被调用。
我不知道为什么一个会被调用而另一个不会。 这是苹果的错误还是我做错了什么?
类似问题:
我在这里找到了一个类似的问题如何在表视图自定义期间调用方法“willDisplayFooterView”?,其中一个答案是:
它们仅在iOS 6.0或更高版本下调用,而且只有在您还实现其他标题/页脚标题/视图方法时才会被调用。如果您提供标题或页脚,则无需调用这些方法。
我不确定我是否正确理解了这个答案,但如果是这样的话,似乎重要的是在子类中实现哪些方法。
代码:
我只发布了我的tableViewController
中非空的覆盖委托和数据源方法:
tvcA.m
@implementation tvcA
...
#pragma mark - Table view data source
- (NSArray *) sectionIndexTitlesForTableView : (UITableView *) tableView
{
// returns sectionIndexArray with alphabet for example
}
- (UIView *) tableView : (UITableView *) tableView
viewForHeaderInSection : (NSInteger) section
{
MNSectionHeaderView* headerView = [[MNSectionHeaderView alloc] initWithFrame : CGRectMake(0, 0, 260, 22)];
return headerView;
}
- (NSInteger) tableView : (UITableView *) tableView
sectionForSectionIndexTitle : (NSString *) title
atIndex : (NSInteger) index {...}
...
@end
tvcB.h(继承自tvcA)
@interface tvcB : tvcA
...
@end
tvcB.m
@implementation tvcB
...
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView : (UITableView *) tableView {...}
- (NSInteger) tableView : (UITableView *) tableView
numberOfRowsInSection : (NSInteger) section {...}
- (UITableViewCell*) tableView : (UITableView *) tableView
cellForRowAtIndexPath : (NSIndexPath *) indexPath {...}
- (CGFloat) tableView : (UITableView *) tableView
heightForHeaderInSection : (NSInteger) section {...}
- (UIView *) tableView : (UITableView *) tableView
viewForHeaderInSection : (NSInteger) section {....}
#pragma mark - Table view delegate
- (void) tableView : (UITableView*) tableView
willDisplayHeaderView : (UIView*) view
forSection : (NSInteger) section {
// custom configurations
}
- (void) tableView : (UITableView*) tableView
didEndDisplayingHeaderView : (UIView*) view
forSection : (NSInteger) section {
// custom configurations
}
- (void) tableView : (UITableView *) tableView
didSelectRowAtIndexPath : (NSIndexPath *) indexPath {...}
...
@end
tableView:viewForHeaderInSection:
每次一个部分标题重新出现在屏幕上时都会被调用 - 在顶部和/或底部。跟踪顶部部分的更简单的方法是:添加一个类属性,如NSUInteger topSection
,并在tableView:viewForHeaderInSection:
中设置它,例如:if(section < _topSection){ _topSection = section;}
,在tableView:didEndDisplayingHeaderView:forSection:nextSectionShown:
中,如果section == _topSection
,则_topSection = nextSection;
。试一下-这样更容易。 - annebluetableView:viewForHeaderInSection:
会被调用来获取所有headerView,而不仅仅是屏幕上的那些。 另外,根据你提出的解决方案,你一直跟踪section,而使用我上面发布的解决方案时,你只在需要时进行检查。 - AXEtableView:viewForHeaderInSection:
正在调用,例如:if (tableView == self.searchDisplayController.searchResultsTableView)...
? - anneblue