Programmatically force a UIScrollView to stop scro

2019-01-16 16:31发布

I have a UITableView whose data source and delegate are switched between a couple of custom data source objects when the user touches a segmented control (think "Top Paid" vs "Top Free" in the app store app).

Each data source object saves its last scroll content offset, and restores it when it becomes the active data source for the table view by doing:

tableView.contentOffset = CGPointMake(0, savedScrollPosition);

This works well when the user switches the data source when the table is at rest, but if the user hits the segmented control while the table is still moving (i.e. decelerating), the table view continues to decelerate from the old offset, effectively overriding my contentOffset assignment.

Is there a way to force the table view to stop scrolling/decelerating when I set the contentOffset, or another way to make this type of switchable-data-source table view work?

10条回答
看我几分像从前
2楼-- · 2019-01-16 17:02

You could wait for the 'decelerating' property to become NO (e.g. by using KVO) and switch after that.

查看更多
趁早两清
3楼-- · 2019-01-16 17:03

This worked nicely for me:

if (self.tableView.isDecelerating) {
        NSArray *paths = [self.tableView indexPathsForVisibleRows];
        [self.tableView scrollToRowAtIndexPath:[paths objectAtIndex:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

    }
查看更多
Root(大扎)
4楼-- · 2019-01-16 17:06

You can also do self.tableView.isScrollEnabled = true/false when you get to a certain tableView.contentOffset.y value

查看更多
太酷不给撩
5楼-- · 2019-01-16 17:07

Have you tried using [view setContentOffset: offset animated: YES]?

查看更多
神经病院院长
6楼-- · 2019-01-16 17:10

One obvious work around is to have two separate table views that get swapped out, and each data source is permanently attached to one of the table views. This just seemed like a bit of a waste of memory, but perhaps I'm over-thinking it.

查看更多
我只想做你的唯一
7楼-- · 2019-01-16 17:14

It was my problem when I had a UISwitch as selector for the tables. But with the segmented control I haven't any problem. Maybe you didn't reload the table? This is my piece of working code:

NSIndexPath *exPath = [[subTable indexPathsForVisibleRows] lastObject]; 

isMatchOn = [whatList selectedSegmentIndex] == 0 ? YES : NO;  //table source will make the choice looking at this BOOL  

[subTable reloadData];  // here tables actually flip

if (lastPosition) {
    [subTable scrollToRowAtIndexPath:lastPosition atScrollPosition:UITableViewScrollPositionBottom animated:NO];   //I scroll to saved index
    }
self.lastPosition = exPath;  //here I save the current position
查看更多
登录 后发表回答