ios - 水平自动滚动 UICollectionviewcell
问题描述
我正在尝试实现 UICollectionView 单元格的水平自动滚动。滚动发生在从第一个索引到第二个索引之后它停止并且 NSTimer 无效。下面是我实现的代码。我究竟做错了什么?集合视图位于 tableviewcell 内。UITableview --- UITableViewCell -- Section 0 -- UI collectionview
- (void)addTimer
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(nextPage) userInfo:nil repeats:NO];
// [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(self.recCollectionView.frame.size.width, self.recCollectionView.frame.size.height);
}
- (void)nextPage
{
@try
{
// 1.back to the middle of sections
NSIndexPath *currentIndexPathReset = [self resetIndexPath];
// 2.next position
NSInteger nextItem = currentIndexPathReset.item + 1;
NSInteger nextSection = currentIndexPathReset.section;
if (nextItem == [[[self.schemeDataDictionary objectForKey:@"data"]objectForKey:delegate.tableString] count]) {
nextItem = 0;
nextSection++;
}
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
// 3.scroll to next position
[self.recCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
@finally {
NSLog(@"finally");
}
}
- (NSIndexPath *)resetIndexPath
{
@try
{
// currentIndexPath
NSIndexPath *currentIndexPath = [[self.recCollectionView indexPathsForVisibleItems] lastObject];
// back to the middle of sections
NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:0/2];
[self.recCollectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
return currentIndexPathReset;
}
@catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
@finally {
NSLog(@"finally");
}
}
- (void)removeTimer
{
[self.timer invalidate];
//self.timer = nil;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self addTimer];
}
解决方案
对于NSTimer
, 设置repeats:NO
为TRUE
Don't add and remove timer in scroll delegates。
推荐阅读
- c# - 如何在按钮文本上显示文本文件中的文本
- java - 使用插入排序时如何将更大的单词放在末尾?
- javascript - JavaScript 功能仅适用于一个 div,而不适用于整个文档
- python - 我想在我在 Reason 中写的数字上赚 5%
- mysql - 创建没有索引的克隆表
- python - 如何为列表中的每个 x、y 点数组着色
- bash - 使用 bash 脚本的小写/大写文件名
- javascript - VUE-COMPOSITION-API:为什么 ref 对 contenteditable 没有反应
- c# - 使用未分配的局部变量“书”
- html - 有什么办法可以将汉堡菜单一直向右移动吗?