У моего проекта есть UIcollectionView. Этот горизонтальный пейджинг и четыре объекта. Я хочу, чтобы моя коллекцияView Auto Scroll Paging. которые используют методы?UICollectionView Auto Scroll Paging
ответ
Что касается теории, я просто объясню ключевой момент. Например, если вы хотите автоматически отображать 5 изображений в любом месте, так же, как панель объявлений. Вы можете создать UICollectionView со 100 разделами, и в каждом разделе есть 5 элементов. После создания UICollectionView установите его исходное положение равным 50-й секции 0-го элемента (в середине MaxSections ), чтобы вы могли прокручивать влево или вправо. Не беспокойтесь, это закончится, потому что я сбросил позицию, равную середине MaxSections, когда работает Таймер. Никогда не спорь со мной: «Это также закончится, когда пользователь будет прокручивать сам». Если найти только 5 изображений, он будет продолжать прокрутку !? Я считаю, что в этом мире мало таких глупых пользователей!
Примечание: В следующих кодах headerView является UICollectionView, headerNews - это данные. И я предлагаю установить MaxSections = 100.
Добавить NSTimer после пользовательского CollectionView (Убедитесь, что UICollectionViewFlowLayout правильно установлен на первом):
- (void)addTimer
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
self.timer = timer;
}
затем реализовать @selector (СледующаяСтраница):
- (void)nextPage
{
// 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.headerNews.count) {
nextItem = 0;
nextSection++;
}
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
// 3.scroll to next position
[self.headerView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}
последний метод реализации resetIndexPath:
- (NSIndexPath *)resetIndexPath
{
// currentIndexPath
NSIndexPath *currentIndexPath = [[self.headerView indexPathsForVisibleItems] lastObject];
// back to the middle of sections
NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:MaxSections/2];
[self.headerView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
return currentIndexPathReset;
}
для того, чтобы кон Троль NSTimer, вы должны выполнить некоторые другие способы и методы делегата UIScrollView в:
- (void)removeTimer
{
// stop NSTimer
[self.timer invalidate];
// clear NSTimer
self.timer = nil;
}
// UIScrollView' delegate method
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self addTimer];
}
Swift версии 2.0 для ответа @Elijah_Lam «s:
func addTimer()
{
timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "nextPage", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
func nextPage()
{
var ar = cvImg.indexPathsForVisibleItems()
///indexPathsForVisibleItems()'s result is not sorted. Sort it by myself...
ar = ar.sort{if($0.section < $1.section)
{
return true
}
else if($0.section > $1.section)
{
return false
}
///in same section, compare the item
else if($0.item < $1.item)
{
return true
}
return false
}
var currentIndexPathReset = ar[1]
if(currentIndexPathReset.section > MaxSections)
{
currentIndexPathReset = NSIndexPath(forItem:0, inSection:0)
}
cvImg.scrollToItemAtIndexPath(currentIndexPathReset, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
}
func removeTimer()
{
// stop NSTimer
timer.invalidate()
}
// UIScrollView' delegate method
func scrollViewWillBeginDragging(scrollView: UIScrollView)
{
removeTimer()
}
func scrollViewDidEndDragging(scrollView: UIScrollView,
willDecelerate decelerate: Bool)
{
addTimer()
}
- 1. UIScrollview scroll paging
- 2. Tvos UICollectionView; no paging
- 3. UICollectionView with Paging
- 4. UICollectionView, paging и clipsToBounds
- 5. UICollectionView scroll single column
- 6. UICollectionView scroll lag
- 7. UICollectionView weird scroll issue
- 8. DIV auto scroll
- 9. NSTextView auto-scroll
- 10. auto scroll chatbox
- 11. Инфраструктура UltraListView auto scroll
- 12. Auto scroll text effect
- 13. Auto scroll down iframe
- 14. Auto Scroll CSS3
- 15. Auto scroll to Bottom
- 16. Auto-Scroll the Webview
- 17. Auto scroll recyclerview slider
- 18. Textfieldshouldreturn auto scroll screen
- 19. Textarea Auto scroll down
- 20. Auto-sizing UICollectionView заголовки
- 21. UICollectionView Auto Height
- 22. Ошибка UICollectionView auto layout
- 23. Pagination on scroll в UICollectionView
- 24. UICollectionView vertical scroll last item
- 25. UICollectionview scroll горизонтальный и вертикальный
- 26. UICollectionview scroll buttom для обновления
- 27. UICollectionView clipsToBounds работает неправильно с paging
- 28. jquery ui draggable scroll auto
- 29. Auto Scroll TextView в CustomListView
- 30. контекстное меню WPF auto scroll
Его показ "Фатальная ошибка: Индекс вне диапазона". – Tuhin