IOS UIScrollView实现自动轮播图功能

本文介绍了一种使用iOS原生技术实现自动轮播图的方法。通过自定义UIView并利用UIScrollView和NSTimer,实现了图片的自动切换及页面指示器功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  LoopScrollImageView.h
//  test07 实现自动轮播图效果
//
//  Created by mouweng on 17/8/26.
//  Copyright © 2017年 mouweng. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface LoopScrollImageView : UIView <UIScrollViewDelegate>
    @property (nonatomic, retain) NSTimer * timer;  //设置定时器
    
    @property (nonatomic, retain) UIScrollView * scrollView;
    @property (nonatomic, retain) UIPageControl * pageControl;
    @property (nonatomic, retain) UILabel * currentPageLabel;
    
    @property (nonatomic, retain) NSArray * dataSource;
    
    
    - (id) initWithFrame:(CGRect)frame images:(NSArray *)images;
    
    - (void) startTimer;
    - (void) stopTimer;


@end


//
//  LoopScrollImageView.m
//  test07 实现自动轮播图效果
//
//  Created by mouweng on 17/8/26.
//  Copyright © 2017年 mouweng. All rights reserved.
//

#import "LoopScrollImageView.h"

@implementation LoopScrollImageView

//重写初始化方法
- (id) initWithFrame:(CGRect)frame images:(NSArray *)images {
    if (self = [super initWithFrame:frame]) {
        self.dataSource = images;
        // 1. 初始化定时器
        _timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(loopImageTimer:) userInfo:nil repeats:YES];
        //[timer setFireDate:[NSDate distantFuture]];
        
        CGFloat viewWidth = CGRectGetWidth(self.frame);
        CGFloat viewHeigh = CGRectGetHeight(self.frame);
        NSUInteger pageCount = images.count;
        
        // 2. 初始化UIScrollView
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, viewWidth, viewHeigh)];
        _scrollView.contentSize = CGSizeMake(viewWidth * pageCount, viewHeigh);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        
        for (int i = 0; i < images.count; i++) {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(viewWidth * i, 0, viewWidth, viewHeigh)];
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.image = [UIImage imageNamed:images[i]];
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loopImageOnClicked:)];
            [imageView addGestureRecognizer:tap];
            
            [_scrollView addSubview:imageView];
        }
        
        [self addSubview:_scrollView];
        
        if (images.count > 1) {
            // 3. 初始化UIPageControl
            int pageControllHeight = 30;
            CGFloat scrollViewBottom = _scrollView.frame.origin.y + _scrollView.frame.size.height;
            _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(10, scrollViewBottom - pageControllHeight, 100, pageControllHeight)];
            _pageControl.currentPage = 0;//当前页数所在的page位置
            _pageControl.numberOfPages = pageCount;
            _pageControl.backgroundColor = [UIColor grayColor];
            [self addSubview:_pageControl];
            
            // 4. 初始化 当前页/总页数
            _currentPageLabel = [[UILabel alloc] initWithFrame:CGRectMake(viewWidth - 50, _pageControl.frame.origin.y, 50, pageControllHeight)];
            _currentPageLabel.text = [NSString stringWithFormat:@"%d/%ld", 1, images.count];
            [self addSubview:_currentPageLabel];
        }
    }
    
    return self;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isMemberOfClass:[UITableView class]]) {
        
    }else {
        int index = fabs(scrollView.contentOffset.x) / scrollView.frame.size.width;   //当前是第几个视图
        _pageControl.currentPage = index;
        
        _currentPageLabel.text = [NSString stringWithFormat:@"%d/%ld", index + 1, self.dataSource.count];
    }
}


//循环定时器设置
#pragma mark - Actions
- (void) loopImageTimer:(NSTimer *)timer {
    NSUInteger totalNum = self.dataSource.count;
    if (totalNum > 1) {
        CGPoint newOffset = _scrollView.contentOffset;
        newOffset.x = newOffset.x + CGRectGetWidth(_scrollView.frame);
        if (newOffset.x > (CGRectGetWidth(_scrollView.frame) * (totalNum-1))) {
            newOffset.x = 0 ;
        }
        int index = newOffset.x / CGRectGetWidth(_scrollView.frame);   //当前是第几个视图
        newOffset.x = index * CGRectGetWidth(_scrollView.frame);
        
        _pageControl.currentPage = index;
        _currentPageLabel.text = [NSString stringWithFormat:@"%d / %ld",index+1, totalNum];
        [_scrollView setContentOffset:newOffset animated:YES];
    }else{
        [_timer setFireDate:[NSDate distantFuture]];//关闭定时器
    }
}


//点击事件
- (void) loopImageOnClicked:(UITapGestureRecognizer *) tapGestureRecognizer{
    NSInteger imageViewTag = tapGestureRecognizer.view.tag;
    NSLog(@"imageViewTag: ----------------- %ld", imageViewTag);        // 0, 1, 2
    
}


//开始和停止
#pragma mark - Methods
- (void) startTimer {
    [_timer setFireDate:[NSDate distantPast]];
}

- (void) stopTimer {
    [_timer setFireDate:[NSDate distantFuture]];
}

@end


//
//  ViewController.m
//  test07 实现自动轮播图效果
//
//  Created by mouweng on 17/8/26.
//  Copyright © 2017年 mouweng. All rights reserved.
//

#import "ViewController.h"
#import "LoopScrollImageView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"UIImage自动轮播";
    
    NSArray *  imageDataSource = [NSArray arrayWithObjects:@"1.jpg", @"2.jpg", @"3.jpg", nil];
    // 只需初始化就可以实现效果
    LoopScrollImageView * loopScrollImageView =[[LoopScrollImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 736) images:imageDataSource];
    [self.view addSubview:loopScrollImageView];
}

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

@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值