You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS滚动时UITableView与替换导航栏的UIView间出现异常白隙问题求助

问题成因

  • 你当前硬编码了tableView偏移量20,没有和替代导航栏的segView高度绑定,偏移量不匹配就会产生间隙
  • tableView的frame修改没有放入动画块,和segView、导航栏的动画不同步,会出现视觉差导致间隙
  • else分支中存在一行无效代码self.initialHeaderRect1.size.height;,无实际作用
  • scrollViewWillBeginDragging方法中强制将传入的scrollView赋值为self.tableView,如果页面有其他滚动视图会导致偏移量计算错误
  • 没有关闭系统对滚动视图的自动内边距调整,导航栏显隐时系统会自动修改tableView的contentInset,额外产生顶部间隙

修复方案

  1. 首先在viewDidLoad中添加代码,关闭系统自动调整滚动视图内边距:
// 适配全iOS版本
if (@available(iOS 11.0, *)) {
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
    self.automaticallyAdjustsScrollViewInsets = NO;
}
  1. 替换原有scrollViewDidScroll和scrollViewWillBeginDragging的代码,修正逻辑:
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 只处理tableView的滚动事件
    if (scrollView != self.tableView) return;
    
    CGFloat scrollPos = scrollView.contentOffset.y;
    CGFloat delta = scrollPos - _currentOffset;
    // 添加滚动阈值,避免微小滚动触发动画
    if (fabs(delta) < 30) return;

    if(delta > 0 ){
        // 向上滚动,隐藏导航栏
        [UIView animateWithDuration:0.50 animations:^{
            self.navigationController.navigationBar.alpha = 0.0f;
            CGRect navBarFrame = self.initialHeaderRect;
            navBarFrame.origin.y -= self.initialHeaderRect.size.height;
            self.navigationController.navigationBar.frame = navBarFrame;
            
            CGRect segFrame = self.initialHeaderRect1;
            segFrame.origin.y -= self.initialHeaderRect1.size.height;
            self.segView.frame = segFrame;
            
            // tableView顶部跟随segView调整,不用硬编码20,直接用segView的高度
            CGRect tableFrame = self.initialTableContainerRect;
            tableFrame.origin.y -= self.initialHeaderRect1.size.height;
            self.tView.frame = tableFrame;
        }];
    } else {
        // 向下滚动,显示导航栏
        [UIView animateWithDuration:0.50 animations:^{
            self.navigationController.navigationBar.alpha = 1.0f;
            self.navigationController.navigationBar.frame = self.initialHeaderRect;
            self.segView.frame = self.initialHeaderRect1;
            self.tView.frame = self.initialTableContainerRect;
        }];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        _currentOffset = scrollView.contentOffset.y;
    }
}
  1. 检查你的segView的父视图是否是当前控制器的view,确保它的层级在tableView之上,避免被tableView遮挡。

内容的提问来源于stack exchange,提问作者stefanosn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:54:01