Reload section without reloading section header

后端 未结 7 594
离开以前
离开以前 2020-12-08 08:03

I have a UITableView, where there is a UISegmentedControl in the header view. It should work exactly like in the App Store app: As the user scrolls

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 08:12

    Here's another way which you could use and still use animations.

    Let's say you have a dynamic DataSource, which changes when you select something, and you want to update just the rows of that section, while leaving the section header on top, untouched.

    /** I get the desired handler from the handler collection. This handler is just a
     simple NSObject subclass subscribed to UITableViewDelegate and UITableViewDataSource
     protocols. **/
    id handler = [self.tableViewHandlers objectForKey:[NSNumber numberWithInteger:index]];
    
    /**  Get the rows which will be deleted  */
    NSInteger numberOfRows = [self.tableView numberOfRowsInSection:sectionIndex];
    NSMutableArray* indexPathArray = [NSMutableArray array];
    
    for (int rowIndex = 0; rowIndex < numberOfRows; rowIndex++){
        [indexPathArray addObject:[NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex]];
    }
    
    /**  Update the handler  */
    [self.tableView setDataSource:handler];
    [self.tableView setDelegate:handler];
    
    /**  Get the rows which will be added  */
    NSInteger newNumberOfRows = [handler tableView:self.tableView numberOfRowsInSection:sectionIndex];
    NSMutableArray* newIndexPathArray = [NSMutableArray array];
    
    for (int rowIndex = 0; rowIndex < newNumberOfRows; rowIndex++){
        [newIndexPathArray addObject:[NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex]];
    }
    
    /**  Perform updates  */
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView insertRowsAtIndexPaths:newIndexPathArray withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
    

    As a note, please stick to the specified order of operations, UITableView demands it. If you have only one handler (datasource and delegate), it's easy to modify the above code to achieve the same results.

提交回复
热议问题