原理是从tableview中取出某个NSindexPath ,比如取出第0个 NSIndexPath *topPath = [self.tableView indexPathForCell:self.tableView.visibleCells.firstObject];
设置新值
self.topSection = topPath.section;
用KVC 来刷新tableview;
@property NSInteger topSection;
- (void)viewDidLoad {
[super viewDidLoad];
[self addObserver:self forKeyPath:@"topSection" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 8;}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SWidth, 8)];
if (section == self.topSection) {
view.backgroundColor = [UIColor redColor];
}else{
view.backgroundColor = [UIColor blackColor];
}
return view;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSIndexPath *topPath = [self.tableView indexPathForCell:self.tableView.visibleCells.firstObject];
self.topSection = topPath.section;
DLog(@"self.topSection:%ld",self.topSection);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"topSection"]) {
[self.tableView reloadData];
//或者(就需要记录新值和旧值)
[self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"topSection"];
}