2014-11-10 3 views
1

У моего проекта есть UIcollectionView. Этот горизонтальный пейджинг и четыре объекта. Я хочу, чтобы моя коллекцияView Auto Scroll Paging. которые используют методы?UICollectionView Auto Scroll Paging

ответ

11

Что касается теории, я просто объясню ключевой момент. Например, если вы хотите автоматически отображать 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]; 

} 
1

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() 
    } 
+0

Его показ "Фатальная ошибка: Индекс вне диапазона". – Tuhin