封装scrollView 循环滚动

今天给大家送点干货:封装的简单实用及介绍,希望大家共同学习共同进步

封装在变成过程中非常重要,可以提高代码的复用性,可以高效的完成项目,并且可以对外部提供接口 

大家可以看一下 封装之前 和封装之后 

viewDidLoad 中的代码量 ,未封装之前 基本上所有的代码都写在了控制器内,十分的麻烦 

封装之后 有少量的代码就可以完成特定的功能!

封装之前:

//
//  QHMainController.m


#import "QHMainController.h"
#import "GPAdsView.h"


@interface QHMainController ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property(nonatomic,strong) NSTimer *timer;
@end

@interface QHMainController()<GPAdsViewDelegate>

@end
@implementation QHMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    int totalPage = 5;
    CGFloat btnW = self.scrollView.frame.size.width;
    CGFloat btnH = self.scrollView.frame.size.height;
    
    for (int i = 0; i < totalPage; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        NSString *name = [NSString stringWithFormat:@"ad_%02d",i];
        UIImage *image = [UIImage imageNamed:name];
        
        [btn setBackgroundImage:image forState:UIControlStateNormal];
        CGFloat btnX = i*btnW;
        CGFloat btnY = 0;

        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        [self.scrollView addSubview:btn];
    }
    
    _scrollView.contentSize = CGSizeMake(totalPage*btnW, btnH);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    //设置代理有两种方式 设置
    _scrollView.delegate = self;
    //设置pageControl的属性
    self.pageControl.numberOfPages = totalPage;
    self.pageControl.currentPage = 0;
    
    [self startTimer];
    
    
#warning 新添加代码
    GPAdsView *adsView = [GPAdsView adsView];
    [self.view addSubview:adsView];
    
    adsView.images = @[@"ad_00",@"ad_01",@"ad_02",@"ad_03",@"ad_04"];
   
    
   // adsView.delegate = self;
    
    [adsView setAdsViewDidSelectedBlock:^(GPAdsView * adsView, NSString * image, NSInteger index) {
        [self adsViewDidSelected:adsView andImage:image andIndex:index];
    }];

}

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)adsViewDidSelected:(GPAdsView *)adsView andImage:(NSString *)image andIndex:(NSInteger)index
{
    NSLog(@"图片名称 %@,索引值是 %ld",image,index);
}
//-(void)adsViewDidSelected:(GPAdsView *)adsView andImage:(NSString *)image andIndex:(NSInteger)index
//{
//    NSLog(@"图片名:%@,索引值:%ld",image,index);
//}

-(void)startTimer
{
     //添加一个定时器
    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
    self.timer = timer;
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.timer invalidate];
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    [self startTimer];
}
-(void)autoScroll
{
    //1.得到偏移量
    //2如何得大滚动的位置
    int totalPage = 5;
    int page = self.pageControl.currentPage >=totalPage -1?0:self.pageControl.currentPage+1;
    self.scrollView.contentOffset = CGPointMake(page*self.scrollView.frame.size.width, 0);

}


//只要发生滚动就会自动调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint contentOffSet = self.scrollView.contentOffset;
    
    int page = (contentOffSet.x + self.scrollView.frame.size.width*0.5)/self.scrollView.frame.size.width;
    
    self.pageControl.currentPage = page;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

封装之后: 

- (void)viewDidLoad {
    [super viewDidLoad];
    
#warning 新增代码
    GPAdsView * adsView = [GPAdsView adsView];

    [self.view addSubview:adsView];
    
    adsView.images = @[@"ad_00",@"ad_01",@"ad_02",@"ad_03",@"ad_04"];
//    adsView.delegate = self;
    [adsView setAdsViewDidSelectedBlock:^(GPAdsView * adsView, NSString * image, NSInteger index) {
        
        [self adsViewDidSelected:adsView andImage:image andIndex:index];
        
    }];

}

下面是封装的view 大家可以参考学习一下,有哪里不合适的大家可以多提建议

代码的注释写了不少 应该基本可以理解

//
//  GPAdsView.h


#import <UIKit/UIKit.h>
#import "UIView+UIViewFrame.h"
/**
 *  设置代理
 */
@class GPAdsView;

@protocol GPAdsViewDelegate <NSObject>

//-(void)adsViewDidSelected:(GPAdsView *)adsView andImage:(NSString *)image andIndex:(NSInteger)index;

- (void)adsViewDidSelected:(GPAdsView *)adsView andImage:(NSString *)image andIndex:(NSInteger)index;

@end



@interface GPAdsView : UIView

+(id)adsView;
@property(nonatomic,copy)void(^adsViewDidSelectedBlock)(GPAdsView * adssView,NSString *image,NSInteger index);
@property(nonatomic,assign)id<GPAdsViewDelegate>delegate;
@property(nonatomic,strong)NSArray *images;//如果想要保存值的话必须用强指针!!!!
@end

//
//  GPAdsView.m
//  练习代码-8-14


#import "GPAdsView.h"
//匿名扩展
@interface GPAdsView()<UIScrollViewDelegate>

@property(nonatomic,weak)UIScrollView *scrollView;
@property(nonatomic,weak)UIPageControl *pageControl;
@property(nonatomic,strong)NSTimer *timer;

@end


@implementation GPAdsView

+(id)adsView
{
    return [[self alloc]init];
}


-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        NSLog(@"调用initWithFrame");
    //1.初始化scrollView
        UIScrollView *scrollView = [[UIScrollView alloc]init];
        scrollView.delegate = self;
        scrollView.pagingEnabled =YES;
        //scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:scrollView];
        self.scrollView = scrollView;
    //2.初始化PageView
        UIPageControl *pageControl = [[UIPageControl alloc]init];
        pageControl.pageIndicatorTintColor = [UIColor greenColor];
        pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        [self addSubview:pageControl];
        self.pageControl = pageControl;
        pageControl.currentPage = 0;
    }
    
    [self startTimer];
    return self;
}
-(void)setImages:(NSArray *)images
{
    _images = images;
    NSLog(@"%@",_images);
    //设置依赖数据的一些属性
    //设置页码数
    self.pageControl.numberOfPages = images.count;
    //设置scrollView 的contentSize 大小
    self.scrollView.contentSize = CGSizeMake(self.frame.size.width*images.count, 0);
    
    for (int i = 0; i < images.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        CGFloat btnW = self.scrollView.width;
        CGFloat btnH = self.scrollView.frame.size.height;
        CGFloat btnX = btnW *i ;
        CGFloat btnY = 0;

        
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        NSString *name = images[i];
        UIImage *image = [UIImage imageNamed:name];
        [btn setBackgroundImage:image forState:UIControlStateNormal];
        
        btn.tag = i;
        
        [self.scrollView addSubview:btn];
        [btn addTarget:self action:@selector(btnTouch:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}



-(void)btnTouch:(UIButton *)btn
{
    NSLog(@"点击事件发生");
//    [_delegate adsViewDidSelected:self andImage:self.images[btn.tag] andIndex:btn.tag];
       [_delegate adsViewDidSelected:self andImage:self.images[btn.tag] andIndex:btn.tag];
    NSLog(@"%@",self.images[btn.tag]);
    NSLog(@"-------------");
    
    if (self.adsViewDidSelectedBlock) {
        self.adsViewDidSelectedBlock(self,self.images[btn.tag],btn.tag);
    }
}

-(void)willMoveToSuperview:(UIView *)newSuperview
{
    //一般抽象出来的都是一个单独的UIView 如果有特殊的需求那么我们会继承 其他的类
    
    //设置View的frame
    CGFloat selfX = 0;
    CGFloat selfY = 0;
    CGFloat selfW = newSuperview.frame.size.width;
    CGFloat selfH = 220;
    
    self.frame = CGRectMake(selfX, selfY, selfW, selfH);
    self.backgroundColor = [UIColor yellowColor];
    
    
    //设置scrollview 的frame
    //self.scrollView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    self.scrollView.frame = self.bounds;
    self.scrollView.backgroundColor = [UIColor yellowColor];
    //设置pageControl 的frame
    self.pageControl.frame = CGRectMake(0,self.frame.size.height-40, self.frame.size.width, 0);
    
}


#pragma 实现基本功能  点击拖动图片,pageContrl 的值发生改变


/**
 *  这里注意不要选错函数,函数的功能和作用都不一样
 *
 *  @param scrollView <#scrollView description#>
 */
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //获得偏移量
    int page = (self.scrollView.contentOffset.x + self.frame.size.width*0.5)/self.frame.size.width;
    
    self.pageControl.currentPage = page;
    
    //NSLog(@"%d",page);
}

#pragma 实现自动滚动的功能 

/**
 *  定时器 这里的定时器选需要注意
 */
-(void)startTimer
{
    // 每隔1秒中就会调用函数autoScroll 我们不用考虑他是怎样实现的
    //要慢慢养成面向对象的变成思想
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES];
    
    //这里设置事件很重要 防止用户交互时产生冲突
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
}

-(void)autoScroll
{
     //怎样使屏幕自动滚动??每当我们遇到问题时候都要思考
    int totalPage = 5;
    int page = self.pageControl.currentPage >= totalPage -1?0:self.pageControl.currentPage + 1;
    self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width*page, 0);
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
   
    [self.timer invalidate];//如果关闭之后无法开启
    
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self startTimer];
}




@end


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
微信小程序中的scroll-view组件是用来实现滚动视图的,但默认情况下并不支持循环滚动。如果需要实现循环滚动,我们可以通过一些自定义的方式来实现。 实现循环滚动的基本思路是在scroll-view组件外面放置一个容器,并在容器中复制一份完整的内容,并且在容器的开始和结束处分别添加一份内容的副本。通过设置容器的宽度为原始内容的宽度加上一份内容的副本的宽度,来实现循环滚动的效果。 具体实现的步骤如下: 1. 在scroll-view组件外部添加一个容器,例如使用view组件包裹scroll-view组件。 2. 获取原始内容的宽度,可以使用小程序的API来获取元素的宽度,如wx.createSelectorQuery().select('#id').boundingClientRect() 3. 复制一份完整的内容,并在容器的开始和结束处分别添加一份内容的副本。 4. 设置容器的宽度为原始内容的宽度加上一份内容的副本的宽度。 5. 在scroll-view组件的bindscroll事件中,通过监听滚动的偏移量,当滚动偏移量超过容器的宽度时,将scroll-view滚动到对应的位置,并且将滚动偏移量重置为0,实现循环滚动的效果。 需要注意的是,滚动的速度要快于内容的切换,否则会出现内容错乱的情况。同时,由于scroll-view组件在滚动到边缘时会有一定的滚动回弹效果,所以在滚动到容器的开始和结束处时会有一小段回弹效果,可以根据具体的需求进行调整和优化。 总结起来,通过在scroll-view组件外部添加一个容器,在容器中复制一份完整的内容并设置容器的宽度,以及通过监听滚动事件来实现滚动偏移量的调整,就可以实现微信小程序中scroll-view循环滚动效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值