美文网首页iOS Developer程序员
IOS UICollectiontView头视图重用问题

IOS UICollectiontView头视图重用问题

作者: slimsallen | 来源:发表于2017-04-19 18:24 被阅读0次

    今天写项目时 用到了collectionview,但是在添加了头视图之后,发现按钮一会能点一会不能点,当我把view背景色变成红色之后,发现上面又覆盖了一层。

    FUGAI.png

    最后用了暴力解决方法

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            
            UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"forIndexPath:indexPath];
            header.backgroundColor = [UIColor redColor];
            
            for (UIView *view in header.subviews) {
                
                
                [view removeFromSuperview];
            }
            
            
            if (indexPath.section == 0) {
    
                self.topLabel.text = @"点我";
                self.topLabel.backgroundColor = [UIColor yellowColor];
                self.topLabel.textAlignment = NSTextAlignmentCenter;
                self.topLabel.font = H15;
                self.topLabel.textColor = [UIColor grayColor];
                [header addSubview:self.topLabel];
    
            }
               return header;
    
        
        }else{
      
            UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header2"forIndexPath:indexPath];
            header.backgroundColor = [UIColor greenColor];
            return header;
        
        }
    
    }
    
    
    

    这里本来想直接return nil 但是发现return nil 之后 直接就挂了 所以又在上面注册了第二个header视图

         [_mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
         [_mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header2"];
    

    添加头视图方法

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
      
    }
    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    }
    
    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    }
    

    目前能想到的方案是这样 不知道大家有没有更好的方案。

    相关文章

      网友评论

        本文标题:IOS UICollectiontView头视图重用问题

        本文链接:https://www.haomeiwen.com/subject/ucuhzttx.html