記_自己做過的輪播器

添加視圖的部分

添加在tableView的headView里

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    [self addChildViewController:self.bannerController];
    
    __weak typeof(self) weakSelf = self;
    self.bannerController.pageControl = ^(NSInteger page){
        weakSelf.pageControl.currentPage = page;
    };
    self.bannerController.pageNumber = ^(NSInteger number){
        weakSelf.pageControl.numberOfPages = number;
    };
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
    [view addSubview:self.bannerController.view];
    [view addSubview:self.pageControl];
    [self.bannerController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(view);
    }];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(view.mas_right).offset(-20);
        make.bottom.mas_equalTo(view.mas_bottom).offset(5);
    }];
    return view;
}

輪播部分 (UICollectionView)

在 .h中的代碼

#import <UIKit/UIKit.h>
#import "BannerModel.h"


@interface BannerController : UICollectionViewController

@property(nonatomic, copy) void(^pageNumber)(NSInteger number);
@property (nonatomic, copy) void(^pageControl)(NSInteger page);

@end



@interface BannerCell : UICollectionViewCell

@property (nonatomic, strong) BannerModel *model;

@end

在 .m 中的代碼

//

//  BannerController.m

//  BAlliance

//

//  Created by FLYU on 16/5/23.

//  Copyright ? 2016年 jack. All rights reserved.

//

import "BannerController.h"

import "HttpLink.h"

import "Masonry.h"

import "UIImageView+WebCache.h"

import "BannerWebController.h"

import "myDataVC.h"

import "IntegerationController.h"

import "User.h"

import "UserDefaultsKV.h"

import "WYHTools.h"

import "HttpLink.h"



@interface BannerController ()

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSArray *bannerList;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) int pageCount;

@end

@implementation BannerController

static NSString * const reuseIdentifier = @"CollectionCell";

- (instancetype)init {
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self = [super initWithCollectionViewLayout:self.flowLayout];
    if (self) {
        self.collectionView.backgroundColor = RGB(255, 255, 255);
    }
    return self;
  }
- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadDta];
    [self prepareForFlowLayout];
    [self.collectionView registerClass:[BannerCell class] forCellWithReuseIdentifier:reuseIdentifier];
  }
- (void)prepareForFlowLayout {
    self.flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, 90);
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
  }

pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
  }

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.bannerList.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    BannerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.model = self.bannerList[indexPath.item];
  //    NSLog(@"當(dāng)前session->%lu   itenm ->%lu", indexPath.section, indexPath.item);
    return cell;
  }
- (void)setBannerList:(NSArray *)bannerList {
    _bannerList = bannerList;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    [self startTimer];
  }
- (void)loadDta {
    [BannerModel bannerIdWithSuccess:^(NSArray *modelList) {
        self.bannerList = modelList;
        if (self.pageNumber) {
            self.pageNumber(modelList.count);
        }
    } error:^(NSError *error) {
        NSLog(@"項(xiàng)目列表 - error -> %@", error);
    }];
  }

pragma mark - timer實(shí)現(xiàn)輪播

- (void)startTimer {
    self.timer = [NSTimer timerWithTimeInterval:2.f target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
  }
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
  }
- (void)nextPage {
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:3 / 2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    NSInteger nextItem = currentIndexPathReset.item +1;
    NSInteger nextSection = currentIndexPathReset.section;
    if (nextItem == self.bannerList.count) {
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    //NSLog(@"%@", nextIndexPath);
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    if (self.pageControl) {
        self.pageControl(nextItem);
    }
  }

pragma mark - scrollView 代理

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    index = index % self.bannerList.count;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:1] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    if (self.pageControl) {
        self.pageControl(index);
    }
  }
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
  }
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
  }

pragma mark -- 點(diǎn)擊cell事件

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BannerModel *model = self.bannerList[indexPath.item];
    //向服務(wù)器提交行為統(tǒng)計(jì)
    User *user = [UserDefaultsKV getUser];
    NSDictionary *paramter = @{@"key" : user._authtoken,
                               @"bannerId" : @(model.BannerId)
                               };
    [[HttpLink sheardHttpLink] httpLinkIsGet:YES baseURLType:2 urlString:@"banner/actionlog.do" parameters:paramter success:^(id data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (![dict[@"status"] isEqualToString:@"200"]) {
            NSLog(@"banner 行為統(tǒng)計(jì)發(fā)送失敗");
        }
    } failure:^(NSError *error) {
        NSLog(@"Banner 行為統(tǒng)計(jì) error->%@",error);
    }];
    // 本地行為跳轉(zhuǎn)   //'1 webview 2 intent/activy 3none'
    if (model.showType == 1) {
        //BannerWebController *webController = [[BannerWebController alloc] init];
        //webController.urlString = model.url;
        //webController.navigationItem.title = model.title;
        //[self.navigationController pushViewController:webController animated:YES];
    } else if (model.showType == 2) {
        if ([model.url isEqualToString:@"MyMessageActivity"]) {
            myDataVC *mydataVC = [[myDataVC alloc] init];
            [self.navigationController pushViewController:mydataVC animated:YES];
            
        } else if ([model.url isEqualToString:@"BuyCerditsActivity"]) {
            IntegerationController *integerationVC = [[IntegerationController alloc] init];
            integerationVC.hidesBottomBarWhenPushed = YES;
            integerationVC.finishedUserDataTask = [self userDataIsFinished];
            [self.navigationController pushViewController:integerationVC animated:YES];
        }
    } else if (model.showType == 3) {
        #pragma mark -- TODO
    }
  }
- (BOOL)userDataIsFinished {
    User *user = [UserDefaultsKV getUser];
    if ([WYHTools isBlankString:user._avatar]) {
        return NO;
    }
    if ([WYHTools isBlankString:user._company]) {
        return NO;
    }
    if ([WYHTools isBlankString:user._rank]) {
        return NO;
    }
    if ([WYHTools isBlankString:user._region]) {
        return NO;
    }
    if ([WYHTools isBlankString:user._type]) {
        return NO;
    }
    return YES;
  }

@end



//**/

//------------------------------------ cell -------------------------------------/

//**/

@interface BannerCell ()

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation BannerCell

- (instancetype)initWithFrame:(CGRect)frame
  {
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareForSubViews];
    }
    return self;
  }
- (void)setModel:(BannerModel *)model {
    _model = model;
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"default_banner"]];
  }
- (void)prepareForSubViews {
    [self.contentView addSubview:self.imageView];
    self.imageView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 90);
  }
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
    }
    return _imageView;
  }

@end





使用collectionVIewController的一些小坑

  • 初始化的時(shí)候一定要添加flowLayout

  • // flowLayout 的常用屬性
    self.flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, 90);
        self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.flowLayout.minimumLineSpacing = 0;
        self.flowLayout.minimumInteritemSpacing = 0;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.bounces = NO;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        self.collectionView.showsVerticalScrollIndicator = NO;
    
  • 一定要注意indexPath.item 不要寫成row不然會崩潰, 且無錯(cuò)誤信息
  • scrollView代理scrollViewDidEndDecelerating當(dāng)減速完成時(shí)調(diào)用
  • collectionView不能直接添加控件, 其子控件會添加到cell上, 且隨cell滾動, 可添加與其同級控件

NStimer的注意

  • timer使用完成重新使用要調(diào)用[self.timer invalidate];, 并賦值為nil

    ?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市舌稀,隨后出現(xiàn)的幾起案子啊犬,更是在濱河造成了極大的恐慌,老刑警劉巖壁查,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件觉至,死亡現(xiàn)場離奇詭異,居然都是意外死亡睡腿,警方通過查閱死者的電腦和手機(jī)语御,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來席怪,“玉大人应闯,你說我怎么就攤上這事」夷恚” “怎么了碉纺?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長刻撒。 經(jīng)常有香客問我骨田,道長,這世上最難降的妖魔是什么声怔? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任态贤,我火速辦了婚禮,結(jié)果婚禮上捧搞,老公的妹妹穿的比我還像新娘抵卫。我一直安慰自己,他們只是感情好胎撇,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布介粘。 她就那樣靜靜地躺著,像睡著了一般晚树。 火紅的嫁衣襯著肌膚如雪姻采。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天爵憎,我揣著相機(jī)與錄音慨亲,去河邊找鬼。 笑死宝鼓,一個(gè)胖子當(dāng)著我的面吹牛刑棵,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播愚铡,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼蛉签,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了沥寥?” 一聲冷哼從身側(cè)響起碍舍,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎邑雅,沒想到半個(gè)月后片橡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淮野,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年捧书,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骤星。...
    茶點(diǎn)故事閱讀 40,013評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鳄厌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出妈踊,到底是詐尸還是另有隱情了嚎,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布廊营,位于F島的核電站歪泳,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏露筒。R本人自食惡果不足惜呐伞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望慎式。 院中可真熱鬧伶氢,春花似錦趟径、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蕾盯,卻和暖如春幕屹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背级遭。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工望拖, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人挫鸽。 一個(gè)月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓说敏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親丢郊。 傳聞我的和親對象是個(gè)殘疾皇子像云,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評論 2 355

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