Reload UICollectionView header or footer?

前端 未结 10 1188
余生分开走
余生分开走 2020-12-08 02:35

I have some data that is fetched in another thread that updates a UICollectionView\'s header. However, I\'ve not found an efficient way of reloading a supplementary view suc

10条回答
  •  温柔的废话
    2020-12-08 03:23

    Here's what I did to update only the section headers that are currently loaded in memory:

    • Add a weakToStrong NSMapTable. When you create a header, add the header as the weakly held key, with the indexPath object. If we reuse the header we'll update the indexPath.
    • When you need to update the headers, you can now enumerate the objects/keys from the NSMapTable as needed.
    
        @interface YourCVController ()
            @property (nonatomic, strong) NSMapTable *sectionHeaders;
        @end
    
        @implementation YourCVContoller
    
        - (void)viewDidLoad {
            [super viewDidLoad];
            // This will weakly hold on to the KEYS and strongly hold on to the OBJECTS
            // keys == HeaderView, object == indexPath
            self.sectionHeaders = [NSMapTable weakToStrongObjectsMapTable];
        }
    
        // Creating a Header. Shove it into our map so we can update on the fly
        - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
        {
            PresentationSectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"presentationHeader" forIndexPath:indexPath];
            // Shove data into header here
            ...
            // Use header as our weak key. If it goes away we don't care about it
            // Set indexPath as object so we can easily find our indexPath if we need it
            [self.sectionHeaders setObject:indexPath forKey:header];
            return header;
        }
    
        // Update Received, need to update our headers
        - (void) updateHeaders {
            NSEnumerator *enumerator = self.sectionHeaders.keyEnumerator;
            PresentationSectionHeader *header = nil;
            while ((header = enumerator.nextObject)) {
                // Update the header as needed here
                NSIndexPath *indexPath = [self.sectionHeaders objectForKey:header];
            }
        }
    
        @end
    

提交回复
热议问题