好的,我对这个想法很感兴趣,所以我制作了一些代码的原型。我需要专门针对您的需求量身定制,但这可能是一个好的开始。首先,您需要对您UICollectionViewCell
的子类进行子类化,以便在单元格内连接IBOutlet
到您的 imageView。然后,您可以参考我的代码片段来帮助您入门。
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageList = @[@"img1.png", @"img2.png", @"img3.png", @"img4.png"];
}
// This assumes your images are inside your Bundle.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:@selector(updateCells:)
userInfo:nil
repeats:YES];
}
- (void)updateCells:(NSTimer *)timer
{
NSArray *visibleIndexPaths = [self.collectionView indexPathsForVisibleItems];
for (NSIndexPath *indexPath in visibleIndexPaths) {
SubclassCollectionViewCell *cell = (SubclassCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[UIView transitionWithView:cell
duration:1.0f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
cell.imageView.image = [self randomImage];
} completion:nil];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
return cell;
}
- (UIImage *)randomImage
{
NSInteger randomNumber = arc4random() % [self.imageList count];
return [UIImage imageNamed:[self.imageList objectAtIndex:randomNumber]];
}
更新:
如果您一次只希望一个单元格随机翻转,则需要在方法中取出for
循环updateCells
。相反,试试这个:
- (void)updateCells:(NSTimer *)timer
{
NSArray *visibleIndexPaths = [self.collectionView indexPathsForVisibleItems];
NSInteger randomIndex = arc4random() % [visibleIndexPaths count];
NSindexPath *randomIndexPath = [NSIndexPath indexPathForItem:randomIndex inSection:0];
SubclassCollectionViewCell *cell = (SubclassCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[UIView transitionWithView:cell
duration:1.0f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
cell.imageView.image = [self randomImage];
}
completion:nil
];
}