iOS 往下滑动 隐藏导航栏 KVO模式
#pragma mark - 上拉隐藏navigation bar
- (void)setupScrollHideNavigationBar {
[self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
}
- (void)removeScrollHideNavigationBar {
[self.tableView removeObserver:self forKeyPath:@"contentOffset"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([object isEqual:self.tableView] && [keyPath isEqualToString:@"contentOffset"]) {
CGFloat newY = [change[@"new"] CGPointValue].y;
CGFloat oldY = [change[@"old"] CGPointValue].y;
float i = newY - oldY; //i>0上滑, i<0下滑
if (self.tableView.contentOffset.y>-64&&self.tableView.contentOffset.y<=24) {//边界条件,此处不精确
if (i<=0&&_isHidding == NO&&self.navigationController.navigationBar.frame.origin.y==20) { //下拉+bar 已经显示的状态,不再移动
return;
}
_isHidding = NO;
self.navigationController.navigationBar.frame = CGRectMake(0, -44-self.tableView.contentOffset.y, 320, 44);
}else if (self.tableView.contentOffset.y > 24) {
if (i>10) {//更改数值大小可以控制触发 navigation bar 的滑动速度
_isHidding = YES;
}else if(i<-10) {
_isHidding = NO;
}else {
}
}
[self.navigationController setNavigationBarHidden:_isHidding animated:YES];
}
}