UICollectionViewCell刷新布局的时候显示混乱

项目中有一个问题,UIcollectionView cell  删除的时候或新增的时候,因为大小不一样,复用会出现好几项问题。 


#import "OJPNewSetPreferenceController.h"
//#import "ClassSeltecterTypeView.h"
#import "OJPNewSetCollectionViewCell.h"
#import "AddWorkCollectionViewCell.h"
#import "OJPNewSetHeaderCollectionReusableView.h"
#import "OJPNewSetCollectionViewFlowLayout.h"
#import "OJPConstants_h.h"
#import "WorkMsgModel.h"
@interface OJPNewSetPreferenceController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray *dataArray;
//@property (nonatomic,strong)ClassSeltecterTypeView *seltecterTypeView;

@end

@implementation OJPNewSetPreferenceController

- (void)viewDidLoad {
//    self.isBack = YES;
    [super viewDidLoad];
    self.navigationItem.title = @"sss";
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"一这是第一个类一",@"一类二",@"一三", nil];
    NSMutableArray *arr4 = [NSMutableArray arrayWithObjects:@"二第一个类",@"二类的第二个数据",@"二类数据三",@"二类四数据",@"二类五", nil];
    NSMutableArray *arr3 = [NSMutableArray array];
    [self arrayAddSomething:[NSArray arrayWithObjects:arr1,arr4,arr3, nil]];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
    label.text = @"选出你关注的零工类型,第一时间获得零工动态信息";
    label.font = [UIFont systemFontOfSize:Width(10.0f)];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = kMainGrayTextColor;
    [self.view addSubview:label];
    
    OJPNewSetCollectionViewFlowLayout *layout = [[OJPNewSetCollectionViewFlowLayout alloc]init];
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.minimumLineSpacing = 20;
    layout.minimumInteritemSpacing = 10;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kNavBarHeight + Height(30), kScreenWidth - Width(30), kScreenHeight - kNavBarHeight - Height(20)) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];

    [self.collectionView registerClass:[OJPNewSetCollectionViewCell class] forCellWithReuseIdentifier:@"OJPNewSetCollectionViewCell"];
    [self.collectionView registerClass:[AddWorkCollectionViewCell class] forCellWithReuseIdentifier:@"AddWorkCollectionViewCell"];
    [self.collectionView registerClass:[OJPNewSetHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"OJPNewSetHeaderCollectionReusableView"];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    
//    [self.collectionView layoutSubviews];
    
    // Do any additional setup after loading the view.
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSArray *array = self.dataArray[section];
    if (array.count<5) {
        return array.count + 1;
    }
    return 5;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
     NSArray *array = self.dataArray[indexPath.section];
    if (indexPath.row == 0 && [array count]<5) {
        AddWorkCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AddWorkCollectionViewCell" forIndexPath:indexPath];
        return cell;
    }
        OJPNewSetCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OJPNewSetCollectionViewCell" forIndexPath:indexPath];
    WorkMsgModel *model;
        if([array count]>4){
          model = array[indexPath.row];
        }else{
          model = array[indexPath.row - 1];
        }
        cell.model = model;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    OJPNewSetHeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"OJPNewSetHeaderCollectionReusableView" forIndexPath:indexPath];
    switch (indexPath.section) {
        case 0:
            headerView.titleLabel.text = @"企业用工";
            break;
        case 1:
            headerView.titleLabel.text = @"个人用工";
            break;
        case 2:
            headerView.titleLabel.text = @"家庭用工";
            break;
        default:
            break;
    }
    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = self.dataArray[indexPath.section];
    NSString *str;
    WorkMsgModel *model;
    if (indexPath.row == 0 && [array count]<5) {
       str = @"  +选择零工类型";
    }else{
        if([array count]>4){
            model = array[indexPath.row];
        }else{
            model = array[indexPath.row - 1];
        }
    }
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13.0f]};  //指定字号
    CGRect rect = [str boundingRectWithSize:CGSizeMake(0, Height(25))/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:dic context:nil];
    if ([str isEqualToString:@"  +选择零工类型"]) {
        NSLog(@"%f",rect.size.width+Width(15)+Width(15));
        return CGSizeMake(rect.size.width+Width(15)+Width(15), 25);
    }
    NSLog(@"%f",model.www+Width(35)+Width(15));
    return CGSizeMake(model.www+Width(35)+Width(15), 25);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), 65);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 20;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = self.dataArray[indexPath.section];
    if (indexPath.row == 0 && [array count]<5) {
        [self showSelectedView];
    }else{
        [self removeFromText:indexPath];
    }
}

-(void)removeFromText:(NSIndexPath*)indexPath{
   
    NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataArray[indexPath.section]];
    NSLog(@"%@",array);
    NSLog(@"%@",self.dataArray);
    
    if (array.count==5) {
        [array removeObjectAtIndex:indexPath.row];
    }else{
        [array removeObjectAtIndex:indexPath.row - 1];
    }
    [self.dataArray replaceObjectAtIndex:indexPath.section withObject:array];
    [self.collectionView reloadData];
    [self.collectionView layoutIfNeeded];
}
-(void)arrayAddSomething:(NSArray *)array{
    self.dataArray = [NSMutableArray array];
    for (int i=0; i<array.count; i++) {
        NSMutableArray *oneArr = [NSMutableArray array];
        NSArray *arr = array[i];
        for (int j=0; j<arr.count; j++) {
            WorkMsgModel *model = [[WorkMsgModel alloc]init];
            model.titleStr = arr[j];
            
            NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13.0f]};  //指定字号
            CGRect rect = [arr[j] boundingRectWithSize:CGSizeMake(0, Height(25))/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                           NSStringDrawingUsesFontLeading attributes:dic context:nil];
            model.www = rect.size.width;
            [oneArr addObject:model];
        }
        [self.dataArray addObject:oneArr];
    }
}



- (void)showSelectedView{
    UIAlertView *alet = [[UIAlertView alloc]initWithTitle:@"ss" message:@"sdfsd" delegate:nil cancelButtonTitle:@"ss" otherButtonTitles: nil];
    [alet show];
    
    
//    self.seltecterTypeView = [[ClassSeltecterTypeView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDirection:1 withClassType:0];
//    self.seltecterTypeView.isDiallelTable = NO;
//    self.seltecterTypeView.isShowShadow = YES;
//    [self.seltecterTypeView reloadAllTableView];
//    [self.view addSubview:self.seltecterTypeView];
//    [self.seltecterTypeView showTypeView];
//
//
//    self.seltecterTypeView.didClickSureButton = ^(BOOL flag) {
//
//    };
    
}
#import "OJPNewSetCollectionViewCell.h"
#import "OJPConstants_h.h"
@implementation OJPNewSetCollectionViewCell

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(Width(5) , 0, self.contentView.frame.size.width - Width(10), Height(25))];
        self.titleLabel.textColor = kMainLightGrayTextColor;
        self.titleLabel.layer.borderColor = kMainGrayTextColor.CGColor;
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.font = [UIFont systemFontOfSize:13.0f];
        self.titleLabel.layer.cornerRadius = 5;
        self.titleLabel.layer.masksToBounds = YES;
        self.titleLabel.layer.borderWidth = 0.6;
        [self.contentView addSubview:self.titleLabel];
        
        
//        UIView *view  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 25)];
//        view.backgroundColor = [UIColor blueColor];
//        [self.contentView addSubview:view];
        
    }
    return self;
}

-(void)setModel:(WorkMsgModel *)model{
    _model = model;
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"  %@    ",model.titleStr]];
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    attch.image = [UIImage imageNamed:@"shanchuBut.png"];
    attch.bounds = CGRectMake(0, -2.5, Width(13), Width(13));
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri appendAttributedString:string];
    self.titleLabel.attributedText = attri;
}

- (void)setBounds:(CGRect)bounds {
    [super setBounds:bounds];
    self.contentView.frame = bounds;
}

-(void)setTitle:(NSString *)title{
   
}

-(void)layoutSubviews{
    self.titleLabel.frame = CGRectMake(Width(5) , 0, self.contentView.frame.size.width - Width(10), Height(25));
//    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(Width(5) , 0, self.contentView.frame.size.width - Width(10), Height(25))];
}

#import "OJPNewSetCollectionViewFlowLayout.h"

@implementation OJPNewSetCollectionViewFlowLayout

- (instancetype)init{
    if (self = [super init]) {
    }
    return self;
}

/**
 * 用来做布局的初始化操作(不建议在init方法中进行布局的初始化操作)
 - 注意:一定要调用[super prepareLayout]
 */
- (void)prepareLayout{
    [super prepareLayout];
    // 水平滚动
//    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//    // 设置内边距
//    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
//    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}




- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
    // 获得super已经计算好的布局属性
  
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    for (int i=0; i<array.count; i++) {
        UICollectionViewLayoutAttributes *attrs = array[i];
//        attrs.representedElementKind
        if (attrs.frame.origin.x>10) {
           UICollectionViewLayoutAttributes *leftAtt = array[i-1];
            CGRect aa = attrs.frame;
            aa.origin.x = leftAtt.frame.origin.x + leftAtt.frame.size.width;
            attrs.frame = aa;
        }
    }
    
    return array;
}

/**
 * 当collectionView的显示范围发生改变的时候,是否需要重新刷新布局
 * 一旦重新刷新布局,就会重新调用下面的方法:
 1.prepareLayout
 2.layoutAttributesForElementsInRect:方法
 */
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

感觉最要注意的是几点

1.    [self.collectionView reloadData];

2. [self.collectionView layoutIfNeeded];

3.- (void)setBounds:(CGRect)bounds {

    [super setBounds:bounds];

    self.contentView.frame = bounds;

}

4.-(void)layoutSubviews{

    self.titleLabel.frame = CGRectMake(Width(5) , 0, self.contentView.frame.size.width - Width(10), Height(25));

}

猜你喜欢

转载自blog.csdn.net/xiaobo0134/article/details/82663590
今日推荐