首页 > 代码库 > 图片轮播器

图片轮播器

?
1
SB里只需要两个控件:

UIScrollView

UIPageControl

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<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