在 UICollectionView 中使用 reloadData 时如何从重新加载中排除 header

How to exclude header from reloading when using reloadData in UICollectionView

我有一个 UICollectionView 使用 CSStickyHeaderFlowLayout 来模仿 UITableView 中的 header 行为。 header里面有SegmentedControl来控制UICollectionView上的数据。所以我想要的是在点击段(调用 API)并执行 reloadData 时重新加载数据,但它总是调用

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

那么只重新加载数据而不是 header 的最佳方法是什么,因为当 reloadData 时 header 也会重新加载,并且段将回到第一个状态.

这是我的 viewForSupplementaryElementOfKind

的代码
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{

UICollectionReusableView *reusableView = nil;

    if (kind == UICollectionElementKindSectionHeader) {
        SegmentHeaderView *collectionHeader= [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Header" forIndexPath:indexPath];
        HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Popular", @"Lelang"]];
        [segmentedControl setFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
        [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
        segmentedControl.backgroundColor = [NConfig FlatButtonGray];
        segmentedControl.selectionIndicatorColor = [UIColor whiteColor];
        segmentedControl.selectionIndicatorBoxOpacity=1;
        segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName : [NConfig FlatButtonOrange]};
        segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName : [NConfig FlatButtonOrange]};
        segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox;
        segmentedControl.selectedSegmentIndex = HMSegmentedControlNoSegment;
        segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationNone;
        segmentedControl.shouldAnimateUserSelection = NO;
        [segmentedControl setSelectedSegmentIndex:0 animated:YES];
        [collectionHeader addSubview:segmentedControl];
        reusableView = collectionHeader;

    }
return reusableView;
}

有什么建议吗? :)

您的错误是您仅将选区存储在视图层中,否则选区可能会丢失。当用户选择不同的段时,您确实应该使用新的选择索引设置 属性。然后你可以通过重新加载你的数据来对这个改变 属性 做出反应。在 return header 视图之前,您将所选段设置为您之前存储的索引。这样选择就不会丢失。

除此之外,您还应该避免重新加载数据,而是只重新加载实际更改的项目。