iOS UICollectionView循環(huán)滾動的輪播界面

記錄下自己項目中用到的循環(huán)輪播功能。

image.png

項目采用UICollectionView來實(shí)現(xiàn)滾動的功能脓恕,頁面類似同花順的股票詳情切換哈肖,點(diǎn)擊列表數(shù)據(jù)的時候展示左右切換按鈕,來實(shí)現(xiàn)標(biāo)題的滾動以及頁面數(shù)據(jù)的重新請求躲履。

@interface StockNavigationView () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *thePreviousBtn;
@property (weak, nonatomic) IBOutlet UIButton *theNextBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *dataAry;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, assign) NSInteger totalItemsCount;

@end

實(shí)現(xiàn)的思路是见间,通過加載比實(shí)際內(nèi)容多的cell來形成左右無限循環(huán)滾動的效果,即self.totalItemsCount = self.dataAry.count * 100;

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.totalItemsCount;
}

因為加載了很多的cell工猜,所以需要通過相應(yīng)的算法來計算準(zhǔn)確的index角標(biāo)值米诉。

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StockNavigationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StockNavigationCell" forIndexPath:indexPath];
    long itemIndex = [self pageControlIndexWithCurrentCellIndex:indexPath.item];
    [cell em_displayWithID:self.dataAry[itemIndex]];

    return cell;
}

通過currentIndex方法計算出UICollectionView當(dāng)前的偏移量,然后通過- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index;方法計算出在實(shí)際數(shù)組self.dataAry內(nèi)的索引值篷帅。

- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index {
    return (int)index % self.dataAry.count;
}

- (int)currentIndex {
    if (_collectionView.frame.size.width == 0 || _collectionView.frame.size.height == 0) {
        return 0;
    }
    
    int index = 0;
    if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        index = (_collectionView.contentOffset.x + _flowLayout.itemSize.width * 0.5) / _flowLayout.itemSize.width;
    } else {
        index = (_collectionView.contentOffset.y + _flowLayout.itemSize.height * 0.5) / _flowLayout.itemSize.height;
    }
    
    return MAX(0, index);
}

然后添加上一頁和下一頁的方法

- (IBAction)thePreviousBtnClick:(id)sender {
    if (0 == _totalItemsCount) return;
    int currentIndex = [self currentIndex];
    int targetIndex = currentIndex - 1;
    [self scrollToIndex:targetIndex];
}

- (IBAction)theNextBtnClock:(id)sender {
    if (0 == _totalItemsCount) return;
    int currentIndex = [self currentIndex];
    int targetIndex = currentIndex + 1;
    [self scrollToIndex:targetIndex];
}

通過- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;方法來滾動到相應(yīng)的位置史侣。

- (void)scrollToIndex:(int)targetIndex {
    if (targetIndex >= _totalItemsCount) {
        targetIndex = _totalItemsCount * 0.5;
        int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:targetIndex];
        NSDictionary *dict = self.dataAry[indexOnPageControl];
        if (self.stockNavigationBlock) {
            self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
        }

        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } completion:^(BOOL finished) {
        int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:targetIndex];
        NSDictionary *dict = self.dataAry[indexOnPageControl];
        if (self.stockNavigationBlock) {
            self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
        }
    }];
//    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

為了在UICollectionView左右手勢滑動的方法中實(shí)現(xiàn)相應(yīng)的功能,我們在- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;方法中實(shí)現(xiàn)了- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;方法魏身,達(dá)到了停止?jié)L動后惊橱,都能產(chǎn)生響應(yīng)。

// 滾動視圖減速完成叠骑,滾動將停止時李皇,調(diào)用該方法。一次有效滑動,只執(zhí)行一次掉房。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidEndScrollingAnimation:self.collectionView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    int itemIndex = [self currentIndex];
    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    NSDictionary *dict = self.dataAry[indexOnPageControl];
    if (self.stockNavigationBlock) {
        self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
    }
}

最后茧跋,只需要在- (void)layoutSubviews;方法中,將self.collectionView滾動到居中的位置即可卓囚。其中self.index為傳入數(shù)組的偏移量瘾杭。

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.collectionView.contentOffset.x == 0 && _totalItemsCount) {
        int targetIndex = _totalItemsCount * 0.5;
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex + self.index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
}

至此,一個簡單循環(huán)滾動功能就完成了哪亿,如果有需要的話粥烁,還可以加上定時器等等等,當(dāng)然了蝇棉,這些都有現(xiàn)成的框架可以用讨阻。

本文中的代碼,參考自SDCycleScrollView的源碼篡殷。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末钝吮,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子板辽,更是在濱河造成了極大的恐慌奇瘦,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件劲弦,死亡現(xiàn)場離奇詭異耳标,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)邑跪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門次坡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人呀袱,你說我怎么就攤上這事贸毕。” “怎么了夜赵?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長乡革。 經(jīng)常有香客問我寇僧,道長,這世上最難降的妖魔是什么沸版? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任嘁傀,我火速辦了婚禮,結(jié)果婚禮上视粮,老公的妹妹穿的比我還像新娘细办。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布笑撞。 她就那樣靜靜地躺著岛啸,像睡著了一般。 火紅的嫁衣襯著肌膚如雪茴肥。 梳的紋絲不亂的頭發(fā)上坚踩,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天,我揣著相機(jī)與錄音瓤狐,去河邊找鬼瞬铸。 笑死,一個胖子當(dāng)著我的面吹牛础锐,可吹牛的內(nèi)容都是我干的嗓节。 我是一名探鬼主播,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼皆警,長吁一口氣:“原來是場噩夢啊……” “哼拦宣!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起耀怜,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤恢着,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后财破,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體掰派,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年左痢,在試婚紗的時候發(fā)現(xiàn)自己被綠了靡羡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡俊性,死狀恐怖略步,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情定页,我是刑警寧澤趟薄,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站典徊,受9級特大地震影響杭煎,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜卒落,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一羡铲、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧儡毕,春花似錦也切、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽疆股。三九已至,卻和暖如春褂萧,著一層夾襖步出監(jiān)牢的瞬間押桃,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工导犹, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留唱凯,地道東北人。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓谎痢,卻偏偏與公主長得像磕昼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子节猿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評論 2 355

推薦閱讀更多精彩內(nèi)容