Skip to main content
 首页 » 操作系统

ios之防止 UITableView 滚动到某个点以下

2024年01月01日49unruledboy

如何让 UITableView 允许在特定索引行上方滚动,但在低于特定点时阻止滚动?例如,如果我有第 1 行到第 100 行,在给定时间只有 5 行出现在 View 中,我想允许用户在第 1-50 行之间滚动,但防止在第 50 行可见时进一步向下滚动。

请您参考如下方法:

为此,您可以使用 UITableView 的属性 contentInset。请记住将它们设置为负值,因为我们正在缩小内容大小:

CGFloat insetTop = topAllowedRow * c_CELL_HEIGHT * -1; 
CGFloat insetBottom = bottomAllowedRow * c_CELL_HEIGHT * -1; 
[self.tableView setContentInset:UIEdgeInsetsMake(insetTop, 0, insetBottom, 0)]; 

另一种解决方案是实现 UIScrollViewDelegate 方法 scrollViewDidScroll: 当 scrollView.contentOffset 太大时,将其设置回最大值该用户可以滚动到:

- (void)scrollViewDidScroll:(UIScrollView*)scrollView { 
    CGPoint scrollViewOffset = scrollView.contentOffset; 
    if (scrollViewOffset.x > MAX_VALUE) { 
        scrollViewOffset.x = MAX_VALUE; 
    } 
    [scrollView setContentOffset:scrollViewOffset]; 
} 

第一个解决方案既有优点也有缺点,因为 UIScrollView 将管理弹跳(就像拉动刷新一样)。它更自然且与 HIG 兼容,但如果您确实需要用户不要看到特定行下方的内容,请使用委托(delegate)方法。