Prevent UITableView scrolling below a certain poin

2020-07-25 09:19发布

How can I have a UITableView that permits scrolling above a certain index row, but prevents it when it below a certain point? For example, if I have rows 1 through 100, where only 5 appear in the view at a given time, I want to allow a user to scroll among rows 1-50, but prevent any further scrolling down when row 50 is visible.

2条回答
劫难
2楼-- · 2020-07-25 09:35

You can use the property contentInset of UITableView just for that. Just remember to set them with minus values, cause we are shrinking the content size:

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

The other solution is to implement UIScrollViewDelegate method scrollViewDidScroll: and when scrollView.contentOffset is too huge, set it back to the max value that user can scroll to:

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

First solution has both the advantage and disadvantage since then UIScrollView will manage the bouncing (just like in pull to refresh). It's more natural and HIG-compatible, but if you really need user not to see below the certain row, use delegate method.

查看更多
戒情不戒烟
3楼-- · 2020-07-25 09:41

UITableView is a subclass of UIScrollView. This means you can use all methods from UIScrollViewDelegate. Try adding the scrollView.contentOffset logic in the following delegate method:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;
查看更多
登录 后发表回答