UICollectionView 刷新布局错乱如何解决
大家好,是不是很多小白和萌新在开发过程中遇到这样的问题,UITableView 刷新用 [_tableView reloadData];好好的,UICollectionView就不是那么回事了,尤其是item的宽度不一样的时候,整个界面惨不忍睹。网上看了很多人都说是cell的服用问题,用这种方式解决:
NSString *identifier=[NSString stringWithFormat:@“cell%ld”,indexPath.row];
if (![[_cellDic allKeys] containsObject:identifier])
{
[_cellDic setValue:identifier forKey:identifier];
[collectionView registerClass:[HomeListCollectionViewCell class] forCellWithReuseIdentifier:identifier];
}
HomeListCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
if (_listArrary.count>0 && _listArrary.count>indexPath.row)
{
cell.title=_listArrary[indexPath.row];
}
return cell;
这样的确实可以解决刷新时布局不变的情况,但是有限制,就是数据不变的情况下才可以,当然数据增加也没事,数据减少你试试,问题就来了,当然有人在数据减少的时候来个 _cellDic=[NSMutableDictionary dictionary];这样只能保证你删除最后一个没事,你如果删除中间的某个数据在刷新就又出问题了,废话不多说,终极解决办法:
@interface HomeListCollectionViewCell()
@property(nonatomic,strong)UILabel *titleLable;
@property(nonatomic,strong)UIImageView *logoImg;
@end
@implementation HomeListCollectionViewCell
-(id)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
if (self) {
[self setupviewcontent];
}
return self;
}
-(void)layoutSubviews
{
[super layoutSubviews];
_titleLable.frame=CGRectMake(5, 0, self.width-25, self.height);
_logoImg.frame=CGRectMake(_titleLable.right+5, (self.height-10)/2, 10, 10);
}
-(void)setupviewcontent
{
self.backgroundColor=BgColor;
self.clipsToBounds=YES;
self.layer.cornerRadius=2.0;
//
_titleLable=[[UILabel alloc]initWithFrame:CGRectMake(5, 0, self.width-25, self.height)];
_titleLable.font=sysfont(12);
_titleLable.textAlignment=NSTextAlignmentLeft;
_titleLable.textColor=middleTextColor;
[self.contentView addSubview:_titleLable];
_logoImg=[[UIImageView alloc]initWithFrame:CGRectMake(_titleLable.right+5, (self.height-10)/2, 10, 10)];
_logoImg.backgroundColor=[UIColor redColor];
[self.contentView addSubview:_logoImg];
}
看明白了么,小伙伴们?没错就是layoutSubviews重写,因为setFrame:(CGRect)frame 这个方法它不走啊,别问我为啥不走,它不走我也没办法不是么_.
如果你们有更好的方法也可以评论留言,风雨人生开发路,一路有你更精彩!