记_自己做过的轮播器

2016-05-24  本文已影响30人  水晶可乐Z

添加视图的部分

添加在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(@"当前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(@"项目列表 - error -> %@", error);
    }];
  }

pragma mark - timer实现轮播

- (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 -- 点击cell事件

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BannerModel *model = self.bannerList[indexPath.item];
    //向服务器提交行为统计
    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 行为统计发送失败");
        }
    } failure:^(NSError *error) {
        NSLog(@"Banner 行为统计 error->%@",error);
    }];
    // 本地行为跳转   //'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的一些小坑

NStimer的注意

上一篇下一篇

猜你喜欢

热点阅读