IOS-图片轮播-使用UIScrollView实现

说明

这里使用了UIScrollView+NSTimer实现,是比较基础的用法。

1.定义需要用到的控件及全局变量

@interface XU_lunbotuView()<UIScrollViewDelegate>

@property(nonatomic,strong) UIView * myView ;
@property(nonatomic,strong) NSTimer * timer ;
@property(nonatomic,strong) UIScrollView * scrollView ;
@property(nonatomic,strong) UILabel * numberLabel;
@property(nonatomic,readwrite) NSInteger x;
@property(nonatomic,readwrite) NSInteger numImageView;

@end

2.初始化创建UIScrollView

UIView * myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self addSubview:myView];
    myView.backgroundColor = [UIColor clearColor];
    self.myView = myView;
    
    //创建UIScrollView
    UIScrollView * scrollView = [UIScrollView new];
    [myView addSubview:scrollView];
    //设置UIscrollView
    scrollView.frame = CGRectMake(0, 0, self.myView.frame.size.width, 260);
    //设置滑动范围
    scrollView.contentSize = CGSizeMake(self.myView.frame.size.width*9, 260);
    //设置水平显示器
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    //设置分页效果
    scrollView.pagingEnabled = YES;
    //设置代理
    scrollView.delegate = self;
    scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView = scrollView;

同时需要实现一下协议

//当滑动快结束的时候  调用些方法
//缓慢结束
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}
//当滑动开始的时候  调用此方法
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
}
//当滑动停止时调用的方法
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
}

3.向scrollview中添加显示 的ImageView

    for(int i = 0 ; i < 9 ; i++) {
        //计算每个UimageView的X轴坐标
        CGFloat imagex = i * self.scrollView.frame.size.width;
        //创建初始化ImageView
        UIImageView * imageView = [UIImageView new];
        [self.scrollView addSubview:imageView];
        //设置Frame
        imageView.frame = CGRectMake(imagex, 0, self.scrollView.frame.size.width, 260);
        //设置imageView背景色
        imageView.backgroundColor = [UIColor colorWithRed:(21*i)/255.0 green:(10*i)/255.0 blue:(15*i)/255.0 alpha:1];
    }

这里使用的是背景颜色,如果需要使用图片则需要

NSBundle *bundle =[NSBundle mainBundle];
    
    //加载 图片路径
    NSString *imagePath = [bundle pathForResource:@"sport.jpg" ofType:nil];
    //加载图片 数据
    NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
    //创建图片
    UIImage *image = [UIImage imageWithData:imageData];

4.添加显示器

使用角标记录,或者小圆点控制显示器

4.1使用小圆点控制显示器

//创建 初始化
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    //设置frame
    pageControl.frame = CGRectMake(70, 200, 200, 200);
    //设置点的个数
    pageControl.numberOfPages=10;
    //设置指示器默认显示的颜色
    pageControl.pageIndicatorTintColor = [UIColor redColor];
    //设置当前选中的颜色
    pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
    //设置当前默认显示位置
    pageControl.currentPage = 0;
    
    //将pageControl添加到视图中    
    [self.view addSubview:pageControl];

4.1.1 设置滑动scrollview切换视图时,对应的小圆点同时切换

//设置pageControl 的显示
//当滑动快结束的时候
//缓慢结束
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //获取当前scrollview 的X轴方向的 偏移量
    CGFloat offset = self.scrollView.contentOffset.x;
    //每个图片页面的宽度
    CGFloat pageWi =self.view.bounds.size.width;
    //设置当前的显示位置
    self.pageControl.currentPage = offset/pageWi+1;
}
这个方法为scrollview的代理协议方法,当滑动scrollview将要结束的时候,会调用此方法,我们可以在这里面做更新小圆点 的操作

4.2使用角标显示页面

    UILabel * numberLabel = [UILabel new];
    [self.myView addSubview:numberLabel];
    [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-15);
        make.right.mas_offset(-9);
        make.height.mas_offset(22);
        make.width.mas_offset(50);
    }];
    numberLabel.textColor = [UIColor whiteColor];
    numberLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightBold];
    [numberLabel.layer  setCornerRadius:11];
    numberLabel.layer.masksToBounds=YES;
    numberLabel.backgroundColor = [UIColor colorWithRed:76/255.0 green:76/255.0 blue:76/255.0 alpha:1];
    numberLabel.textAlignment = NSTextAlignmentCenter;
    self.numberLabel = numberLabel;
    //计算图片的个数
    self.numImageView = self.scrollView.contentSize.width/self.scrollView.frame.size.width;
    NSString * str = [[NSString alloc]initWithFormat:@"1/%ld",self.numImageView];
    numberLabel.text = str;

4.2.1 设置滑动scrollview切换视图时,对应的角标数字转换

//当滑动快结束的时候,调用这些方法
//缓慢结束
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //获取当前scrollView的x轴方向的偏移量
    CGFloat offset = self.scrollView.contentOffset.x;
    //每个图片的宽度
    CGFloat pageWi = self.scrollView.frame.size.width;
    //当前显示位置
    self.x =(offset/pageWi)+1;
    [self textImageView];
}

转换方法

//设置当前显示位置
-(void)textImageView
{
   
    NSString * str = [[NSString alloc]initWithFormat:@"%ld/%ld",self.x,self.numImageView];
    self.numberLabel.text = str;
}

5.设置图片的自动循环播放

创建定时器

-(void)initTimerFunction{
    //创建计时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(autoSelectPage) userInfo:nil repeats:YES];
    NSRunLoop *mainLoop = [NSRunLoop mainRunLoop];
    
    [mainLoop addTimer:timer forMode:NSRunLoopCommonModes];
    
    self.timer = timer;
}

在这里,定时器会每隔两秒钟的时间来重复执行autoSelectPage方法
小圆点控制

-(void)autoSelectPage{
    //取出当前的偏移量
    CGPoint offset =  self.scrollView.contentOffset;
    //取出当前的设置显示 的page指示
    NSInteger  currentPage = self.pageControl.currentPage;
    
    if (currentPage == 9) {
        //设置为初始值
        currentPage =0;
        offset = CGPointZero;
        //更新offset
        [self.scrollView setContentOffset:offset animated:NO];
    }else{
        currentPage++;
        offset.x +=self.view.bounds.size.width;
        //更新offset
        [self.scrollView setContentOffset:offset animated:YES];
    }
    //更新pageControl显示
    self.pageControl.currentPage = currentPage;
    
}

角标显示

-(void)autoSelectPage
{
    //取出当前的偏移量
    CGPoint offset = self.scrollView.contentOffset;
    //取出当前的设置显示
    NSInteger y = self.x;
    
    if (y == self.numImageView) {
        //设置为初始值
        self.x = 1;
        offset = CGPointZero;
        //更新offset
        [self.scrollView setContentOffset:offset animated:YES];
    }else{
        self.x++;
        offset.x +=self.scrollView.frame.size.width;
        //更新offset
        [self.scrollView setContentOffset:offset animated:YES];
    }
    [self textImageView];
}

6、当手势滑动scrollview的时候停止定时器任务,滑动结束的时候开启定时任务

//当滑动开始的时候 ,停止计数器
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //取消定时器任务
    [self.timer invalidate];
}
//当滑动停止时启动定时器任务
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.timer fire];
    //设置自动滚动定时任务
    [self initTimerFunction];
}

转载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 `UICollectionView` 或 `UIPageViewController` 来实现 iOS 图片轮播使用 `UICollectionView` 实现的方法如下: 1. 在您的视图控制器中,创建一个 `UICollectionView` 实例,并将其作为子视图添加到您的视图控制器的视图中。 2. 使用自定义布局实现循环滚动。可以参考以下代码: ``` class LoopCollectionViewFlowLayout: UICollectionViewFlowLayout { override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) } let collectionViewSize = collectionView.bounds.size let proposedContentOffsetCenterX = proposedContentOffset.x + collectionViewSize.width * 0.5 let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionViewSize.width, height: collectionViewSize.height) guard let layoutAttributes = layoutAttributesForElements(in: proposedRect) else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity) } let centerX = proposedContentOffsetCenterX let offset = CGPoint(x: proposedContentOffset.x + nearestTargetOffset(for: layoutAttributes, with: centerX), y: proposedContentOffset.y) return offset } private func nearestTargetOffset(for layoutAttributes: [UICollectionViewLayoutAttributes], with centerX: CGFloat) -> CGFloat { let targetAttributes = layoutAttributes.sorted { abs($0.center.x - centerX) < abs($1.center.x - centerX) } let nearestAttribute = targetAttributes.first return nearestAttribute?.center.x ?? 0 - centerX } } ``` 3. 创建自定义 `UICollectionViewCell` 类,并在其中添加一个 `UIImageView` 用于显示图片。 4. 实现 `UICollectionViewDataSource` 协议中的方法,用于设置图片数据源和自定义的 `UICollectionViewCell`。 5. 实现定时器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值