<br><br><br> @interface
LYViewController () <UIScrollViewDelegate>
/** scrollView */
@property
(weak, nonatomic ) IBOutlet
UIScrollView *scrollVIew;
/** 图片页数 */
@property
(weak, nonatomic ) IBOutlet
UIPageControl *pageNumber;
/** timer */
@property
( nonatomic , strong) NSTimer
*timer;
@end
@implementation
LYViewController
- ( void )viewDidLoad
{
[ super
viewDidLoad];
// 设置图片
for
( int i = 0; i < kImageCount; i ++) {
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(i * kWidth, 0, kWidth, kHeight);
NSString
*imageName = [ NSString
stringWithFormat:@ "img_%02d" , i+1];
imageView.image = [UIImage imageNamed:imageName];
[ self .scrollVIew addSubview:imageView];
}
// 滚动效果
self .scrollVIew.contentSize = CGSizeMake(kImageCount * kWidth, kHeight);
// 取消垂直方向的滚动条
self .scrollVIew.showsVerticalScrollIndicator = NO ;
// 半自动分页
self .scrollVIew.pagingEnabled = YES ;
// 设置代理
self .scrollVIew.delegate = self ;
// 自动播放
[ self
startTimer];
}
#pragma mark 代理方法
- ( void )nextImage
{
if
( self .pageNumber.currentPage == kImageCount - 1) {
self .pageNumber.currentPage = 0;
} else {
self .pageNumber.currentPage ++;
}
CGFloat currentX = kWidth * ( self .pageNumber.currentPage);
// 设置手机屏幕的位置
[ self .scrollVIew setContentOffset:CGPointMake(currentX, 0) animated: YES ];
}
// 只要图片滚动,就会计算图片当前页数
- ( void )scrollViewDidScroll:(UIScrollView *)scrollView
{
if
(! self .timer) {
// 设置图片页数
CGFloat currentX = self .scrollVIew.contentOffset.x;
self .pageNumber.currentPage = (currentX + kWidth * 0.5) / kWidth;
}
}
// 拖动时,关闭计时器
- ( void )scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[ self .timer invalidate];
self .timer = nil ;
}
// 结束拖动,开始计时器
- ( void )scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:( BOOL )decelerate
{
[ self
startTimer];
}
// 开启计时器方法
- ( void )startTimer
{
self .timer = [ NSTimer
timerWithTimeInterval:1.f target: self
selector: @selector (nextImage) userInfo: nil
repeats: YES ];
[[ NSRunLoop
mainRunLoop] addTimer: self .timer forMode: NSRunLoopCommonModes ];
}
@end
|