Programmatically force a UIScrollView to stop scrolling, for sharing a table view with multiple data sources

前端 未结 10 941
醉话见心
醉话见心 2020-12-08 03:04

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\"

相关标签:
10条回答
  • 2020-12-08 03:48

    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.

    0 讨论(0)
  • 2020-12-08 03:49

    I used Corey's approach. I save & restore the rects with the dictionary representation. Also, it may not be obvious but the rect to preserve & restore is the bounds of the UITableView:

    // Save the current tableview bounds
    CGRect contentRect = self.listTableView.bounds;
    if (!!oldScope) [_contentRects setObject:(NSObject *)CGRectCreateDictionaryRepresentation(contentRect) forKey:oldScope];
    
    // Restore if possible
    CFDictionaryRef restoredFrameDict = (CFDictionaryRef)[_contentRects objectForKey:newScope];
    if (!restoredFrameDict) restoredFrameDict = CGRectCreateDictionaryRepresentation(CGRectZero);
    CGRectMakeWithDictionaryRepresentation(restoredFrameDict, &contentRect);
    
    // Switch over to new datasource
    self.listTableView.dataSource = [self dataSourceForScope:newScope];
    [self.listTableView reloadData];
    
    // Restore content offset for "newScope"; Also stops scrolling
    [self.listTableView scrollRectToVisible:contentRect animated:NO];
    

    Note the interchangeable use of CFDictionaryRef and NSDictionary *

    0 讨论(0)
  • 2020-12-08 03:50

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

    0 讨论(0)
  • 2020-12-08 03:52

    Just found this looking for a way to stop my UIScrollView - I needed to move some subviews around, but this wound't look right if the user had flicked the screen and it was still decelerating.

    Anyway - scrollRectToVisible didn't work for me (maybe because I'm not using a table view??) but this worked perfectly:

    [mainScrollView setContentOffset:CGPointMake(mainScrollView.contentOffset.x, mainScrollView.contentOffset.y) animated:NO];
    

    I can then do the subview stuff without worrying!

    0 讨论(0)
提交回复
热议问题