collectionView實現(xiàn)廣告欄滑動功能

一、背景
效果:


video_22.gif

原本以為用collectionView實現(xiàn)很方便,發(fā)現(xiàn)使用page屬性或者自己控制都達不到理想效果。下面通過修改flowLayout的方式實現(xiàn):

#import "FDMBannerFlowLayout.h"

@interface FDMBannerFlowLayout()
@property (nonatomic, assign) UIEdgeInsets sectionInsets;
@property (nonatomic, assign) CGFloat miniLineSpace;
@property (nonatomic, assign) CGFloat miniInterItemSpace;
@property (nonatomic, assign) CGSize eachItemSize;
@property (nonatomic, assign) BOOL scrollAnimation;/**<是否有分頁動畫*/
@property (nonatomic, assign) CGPoint lastOffset;/**<記錄上次滑動停止時contentOffset值*/
@end

@implementation FDMBannerFlowLayout

/*初始化部分*/
- (instancetype)initWithSectionInset:(UIEdgeInsets)insets andMiniLineSapce:(CGFloat)miniLineSpace andMiniInterItemSpace:(CGFloat)miniInterItemSpace andItemSize:(CGSize)itemSize
{
    self = [self init];
    if (self) {
        //基本尺寸/邊距設(shè)置
        self.sectionInsets = insets;
        self.miniLineSpace = miniLineSpace;
        self.miniInterItemSpace = miniInterItemSpace;
        self.eachItemSize = itemSize;
//        self.scrollAnimation = YES;
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _lastOffset = CGPointZero;
    }
    return self;
}

-(void)prepareLayout
{
    [super prepareLayout];
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;// 水平滾動
    /*設(shè)置內(nèi)邊距*/
    self.sectionInset = _sectionInsets;
    self.minimumLineSpacing = _miniLineSpace;
    self.minimumInteritemSpacing = _miniInterItemSpace;
    self.itemSize = _eachItemSize;
    /**
     * decelerationRate系統(tǒng)給出了2個值:
     * 1. UIScrollViewDecelerationRateFast(速率快)
     * 2. UIScrollViewDecelerationRateNormal(速率慢)
     * 此處設(shè)置滾動加速度率為fast,這樣在移動cell后就會出現(xiàn)明顯的吸附效果
     */
    self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast;
}

/**
 * 這個方法的返回值,就決定了collectionView停止?jié)L動時的偏移量
 */
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    CGFloat pageSpace = [self stepSpace];//計算分頁步距
    //最后一頁左邊的offsetX的值,實際滑不到這個值,用它是為了滑到最后一個時,往回滑可以正確計算前一個值
    CGFloat contentWidth = self.collectionView.contentSize.width-(self.sectionInset.right+self.sectionInset.left);
    CGFloat offsetMax = contentWidth - self.eachItemSize.width;
    //x實際能到達的最大距離
    CGFloat realOffsetMax = contentWidth - (self.collectionView.size.width-self.sectionInset.right);
    CGFloat offsetMin = 0;
    /*修改之前記錄的位置,如果小于最小contentsize或者大于最大contentsize則重置值*/
    if (proposedContentOffset.x<offsetMin)
    {
        proposedContentOffset.x = offsetMin;
    }
    if (proposedContentOffset.x>=realOffsetMax)
    {
        //已經(jīng)是最后一頁了
        //就算設(shè)置的x值大于realOffsetMax,最終也是滑到realOffsetMax的位置
        proposedContentOffset.x = offsetMax;
    }
    
    CGFloat offsetForCurrentPointX = ABS(proposedContentOffset.x - _lastOffset.x);//目標位移點距離當前點的距離絕對值
    CGFloat velocityX = velocity.x;
    BOOL direction = (proposedContentOffset.x - _lastOffset.x) > 0;//判斷當前滑動方向,手指向左滑動:YES;手指向右滑動:NO
    
    if (offsetForCurrentPointX > pageSpace/6.0)
    {
        NSInteger pageFactor = 0;//分頁因子,用于計算滑過的cell個數(shù)
        if (velocityX != 0)
        {
            //不是拖動,就有速度,速度為滑動多少頁
            pageFactor = ABS(velocityX);//速率越快,cell滑過數(shù)量越多
        }
        else
        {
            //拖動
            pageFactor = ABS(offsetForCurrentPointX/pageSpace);
        }

        /*設(shè)置pageFactor上限為2, 防止滑動速率過大,導(dǎo)致翻頁過多*/
        pageFactor = pageFactor<1?1:(pageFactor<3?1:2);

        CGFloat pageOffsetX = pageSpace*pageFactor;
        proposedContentOffset = CGPointMake(_lastOffset.x + (direction?pageOffsetX:-pageOffsetX), proposedContentOffset.y);
    }
    else
    {
        /*滾動距離,小于翻頁步距一半,則不進行翻頁操作*/
        proposedContentOffset = CGPointMake(_lastOffset.x, _lastOffset.y);
    }
    if (proposedContentOffset.x>offsetMax)
    {
        proposedContentOffset.x = offsetMax;
    }
    //記錄當前最新位置
    _lastOffset.x = proposedContentOffset.x;
    
    return proposedContentOffset;
}

/**
 *計算每滑動一頁的距離:步距
 */
-(CGFloat)stepSpace
{
    return self.eachItemSize.width + self.miniLineSpace;
}

/**
 * 當collectionView的顯示范圍發(fā)生改變的時候,是否需要重新刷新布局
 * 一旦重新刷新布局,就會重新調(diào)用 layoutAttributesForElementsInRect:方法
 */
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

/**
 *防止報錯先復(fù)制attributes
 */
- (NSArray *)getCopyOfAttributes:(NSArray *)attributes
{
    NSMutableArray *copyArr = [NSMutableArray new];
    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        [copyArr addObject:[attribute copy]];
    }
    return copyArr;
}

/**
 *設(shè)置放大動畫
 */
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    /*獲取rect范圍內(nèi)的所有subview的UICollectionViewLayoutAttributes*/
    NSArray *arr = [self getCopyOfAttributes:[super layoutAttributesForElementsInRect:rect]];

    /*動畫計算*/
    if (self.scrollAnimation)
    {
        /*計算屏幕中線*/
        CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width/2.0f;
        /*刷新cell縮放*/
        for (UICollectionViewLayoutAttributes *attributes in arr) {
            CGFloat distance = fabs(attributes.center.x - centerX);
            /*移動的距離和屏幕寬度的的比例*/
            CGFloat apartScale = distance/self.collectionView.bounds.size.width;
            /*把卡片移動范圍固定到 -π/4到 +π/4這一個范圍內(nèi)*/
            CGFloat scale = fabs(cos(apartScale * M_PI/4));
            /*設(shè)置cell的縮放按照余弦函數(shù)曲線越居中越趨近于1*/
            CATransform3D plane_3D = CATransform3DIdentity;
            plane_3D = CATransform3DScale(plane_3D, 1, scale, 1);
            attributes.transform3D = plane_3D;
        }
    }
    return arr;
}
@end

使用collectionView加載flowLayout:

#import "FDMBaseBannerView.h"
#import "FDMBannerFlowLayout.h"

@interface FDMBaseBannerView()
{
    
}
@property(nonatomic) FDMBannerFlowLayout *flowLayout;
@property(nonatomic) UICollectionView *collectionView;

@end

@implementation FDMBaseBannerView

- (instancetype)initWithSectionInset:(UIEdgeInsets)insets andMiniLineSapce:(CGFloat)miniLineSpace andItemSize:(CGSize)itemSize{
    if(self = [super init]){
        self.flowLayout = [[FDMBannerFlowLayout alloc] initWithSectionInset:insets andMiniLineSapce:miniLineSpace andMiniInterItemSpace:0 andItemSize:itemSize];
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    self.dataArr = @[@"page1",@"page2",@"page3",@"page4",@"page5",@"page6",@"page7",@"page8"];
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}

#pragma -mark UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

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

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
    NSInteger row = indexPath.row%self.dataArr.count;
    NSString *str = self.dataArr[row];
//
    UILabel *lab = [cell.contentView viewWithTag:10];
    if(!lab){
        lab = [[UILabel alloc] init];
        lab.tag = 10;
        [cell.contentView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(0);
        }];
    }
    
    lab.text = str;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@">>>>>>>>>>%zi",indexPath.row);
}


#pragma -mark getting
- (UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionView *collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        //代理設(shè)置
        collect.delegate = self;
        collect.dataSource = self;
        collect.showsVerticalScrollIndicator = NO;
        collect.showsHorizontalScrollIndicator = NO;
        collect.decelerationRate = UIScrollViewDecelerationRateFast;
    //    collect.pagingEnabled = YES;
    //    collect.delaysContentTouches = NO;
    //    collect.canCancelContentTouches = NO;
    //    layout.itemSize = CGSizeMake(collect.frame.size.width-100, collect.frame.size.height);
        //注冊item類型 這里使用系統(tǒng)的類型
        [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
        
        _collectionView = collect;
    }
    return _collectionView;
}

@end

運用:

    CGFloat collectH = 120;
    CGFloat itemW = 200;
//    UIEdgeInsets sectionInset = UIEdgeInsetsMake(0, (iScreenW-itemW)/2, 0, (iScreenW-itemW)/2);
    UIEdgeInsets sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.bannerView = [[FDMBaseBannerView alloc] initWithSectionInset:sectionInset andMiniLineSapce:10 andItemSize:CGSizeMake(itemW, collectH)];
    [self.view addSubview:self.bannerView];
    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.leading.trailing.mas_equalTo(0);
        make.top.mas_equalTo(100);
        make.height.mas_equalTo(collectH);
    }];

如果想實現(xiàn)滑動過程中可以看到左邊劃走的內(nèi)容,可以通過控制edgeInset.left和right實現(xiàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容