我有一个自定义的UICollectionView子类和自定义的UICollectionViewCells。 问题是,当我滚动集合视图时,它会改变项目的位置,如下所示:
滚动前 -
向下滚动然后回到顶部 - (注意Modesto和Rebecka如何改变位置)
UICollectionView子类非常清楚:
#import "MyCustomCollectionViewController.h"
@interface MyCustomCollectionViewController ()
@end
@implementation MyCustomCollectionViewController
static NSString * const reuseIdentifier = @"cell";
-(id)initWithPins:(NSArray*)someArrayOfStuff {
self = [super initWithNibName:@"MyCustomCollectionViewController" bundle:nil];
if (self) {
if (myArray) {
myArray = [[NSMutableArray alloc] initWithArray:someArrayOfStuff];
}
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.collectionView registerClass:[MyCustomCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
[self.collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return myArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
MyCustomCollectionViewCell *cell = (MyCustomCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
MyCustomObject *obj = (MyCustomObject*)[myArray objectAtIndex:indexPath.row];
[cell setObject:obj];
return cell;
}
#pragma mark <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize cellSize = CGSizeMake(self.view.frame.size.width/2, self.view.frame.size.width/2);
return cellSize;
}
,这是我的自定义UICollectionViewCell
#import "MyCustomCollectionViewCell.h"
@implementation MyCustomCollectionViewCell
@synthesize theObject;
@synthesize mediaView;
- (void)awakeFromNib {
mediaView = [[UIImageView alloc] initWithFrame:self.contentView.frame];
mediaView.backgroundColor = self.backgroundColor;
[self.contentView addSubview:mediaView];
}
-(id)initWithFrame:(CGRect)frame {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyCustomCollectionViewCell" owner:nil options:nil];
self = [topLevelObjects objectAtIndex:0];
if (self) {
self.frame = frame;
}
return self;
}
-(void)prepareForReuse {
[mediaView setMediaWithObject:theObject];
}
-(void)setObject:(MyCustomObject*)obj {
if (!theObject) {
theObject = obj;
[mediaView setMediaWithObject:obj];
}
}
@end
我确定有一些显而易见的东西,但我无法弄清楚是什么。感谢。
答案 0 :(得分:2)
试试这个:
-(void) prepareForReuse {
[super prepareForReuse];
[mediaView setMediaWithObject:nil];
}
答案 1 :(得分:0)
我认为你必须在
if (!theObject) {
theObject = obj;
[mediaView setMediaWithObject:obj];
} else {
[mediaView setMediaWithObject:theObject]
}
MyCustomCollectionViewCell.m
的错误条件
祝你好运