IOS轮播图实现方式相对Android实现方式还是简单许多的!!代码比较简单下面会给出Demo
//
// ViewController.m
// ScrollView轮播图
//
// Created by gaocai on 16/7/24.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *page;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat scrollWidth = _scrollView.frame.size.width;
CGFloat scrollHeight = _scrollView.frame.size.height;
int count = 5;
for (int i = 0; i < count; i ++) {
UIImageView *imageView = [[UIImageView alloc] init];
NSString *name = [NSString stringWithFormat:@"img_0%d", i + 1];
imageView.image = [UIImage imageNamed:name];
imageView.frame = CGRectMake(scrollWidth * i, 0, scrollWidth, scrollHeight);
[imageView setBackgroundColor:[UIColor grayColor]];
[self.scrollView addSubview:imageView];
}
_scrollView.contentSize = CGSizeMake(scrollWidth * count, scrollHeight);
_scrollView.pagingEnabled = YES;
//设置page背景图片 因为是私有变量所以通过KVC方式赋值
[_page setValue:[UIImage imageNamed:@"other"] forKey:@"_currentPageImage"];
[_page setValue:[UIImage imageNamed:@"current"] forKey:@"pageImage"];
[_page setNumberOfPages:count];
//当页数为一是隐藏
_page.hidesForSinglePage = YES;
[self startTimer];
}
/**
* 开启定时器
*/
- (void) startTimer {
_timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(changePage) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
/**
* 关闭定时器
*/
- (void)stopTimer {
[_timer invalidate];
}
/**
* 改变currentPage
*/
- (void)changePage {
NSInteger page = self.page.currentPage + 1;
if (page == 5) {
page = 1;
}
[_scrollView setContentOffset:CGPointMake(page * _scrollView.frame.size.width, 0) animated:YES];
}
#pragma mark - scrollView 代理方法
//当ScrollView滚动结束时调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
int current = (scrollView.contentOffset.x / scrollView.frame.size.width + 0.5);
[_page setCurrentPage:current];
}
//当用户开始拖拽时调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self startTimer];
}
//当用户结束拖拽是调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
[self stopTimer];
}
@end