-
Notifications
You must be signed in to change notification settings - Fork 8
/
SDCycleScrollView.m
executable file
·331 lines (270 loc) · 11.1 KB
/
SDCycleScrollView.m
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//
// SDCycleScrollView.m
// SDCycleScrollView
//
// Created by aier on 15-3-22.
// Copyright (c) 2015年 GSD. All rights reserved.
//
/**
*******************************************************
* *
* 感谢您的支持, 如果下载的代码在使用过程中出现BUG或者其他问题 *
* 您可以发邮件到[email protected] 或者 到 *
* https://github.com/gsdios?tab=repositories 提交问题 *
* *
*******************************************************
*/
#import "SDCycleScrollView.h"
#import "SDCollectionViewCell.h"
#import "UIView+SDExtension.h"
#import "TAPageControl.h"
#import "NSData+SDDataCache.h"
NSString * const ID = @"cycleCell";
@interface SDCycleScrollView () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, weak) UICollectionView *mainView; // 显示图片的collectionView
@property (nonatomic, weak) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *imagesGroup;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger totalItemsCount;
@property (nonatomic, weak) TAPageControl *pageControl;
@end
@implementation SDCycleScrollView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self initialization];
[self setupMainView];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
[self initialization];
[self setupMainView];
}
return self;
}
- (void)initialization
{
_pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
_autoScrollTimeInterval = 2.0;
_titleLabelTextColor = [UIColor whiteColor];
_titleLabelTextFont= [UIFont systemFontOfSize:14];
_titleLabelBackgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
_titleLabelHeight = 30;
self.backgroundColor = [UIColor lightGrayColor];
}
+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imagesGroup:(NSArray *)imagesGroup
{
SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
cycleScrollView.imagesGroup = [NSMutableArray arrayWithArray:imagesGroup];
return cycleScrollView;
}
+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imageURLsGroup:(NSArray *)imageURLsGroup
{
SDCycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
cycleScrollView.imageURLsGroup = [NSMutableArray arrayWithArray:imageURLsGroup];
return cycleScrollView;
}
- (void)setFrame:(CGRect)frame
{
[super setFrame:frame];
_flowLayout.itemSize = self.frame.size;
}
- (void)setPageControlDotSize:(CGSize)pageControlDotSize
{
_pageControlDotSize = pageControlDotSize;
_pageControl.dotSize = pageControlDotSize;
}
- (void)setDotColor:(UIColor *)dotColor
{
_dotColor = dotColor;
_pageControl.dotColor = dotColor;
}
- (void)setAutoScrollTimeInterval:(CGFloat)autoScrollTimeInterval
{
_autoScrollTimeInterval = autoScrollTimeInterval;
[_timer invalidate];
_timer = nil;
[self setupTimer];
}
// 设置显示图片的collectionView
- (void)setupMainView
{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.itemSize = self.frame.size;
flowLayout.minimumLineSpacing = 0;
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
_flowLayout = flowLayout;
UICollectionView *mainView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:flowLayout];
mainView.backgroundColor = [UIColor clearColor];
mainView.pagingEnabled = YES;
mainView.showsHorizontalScrollIndicator = NO;
mainView.showsVerticalScrollIndicator = NO;
[mainView registerClass:[SDCollectionViewCell class] forCellWithReuseIdentifier:ID];
mainView.dataSource = self;
mainView.delegate = self;
[self addSubview:mainView];
_mainView = mainView;
}
- (void)setImagesGroup:(NSMutableArray *)imagesGroup
{
_imagesGroup = imagesGroup;
_totalItemsCount = imagesGroup.count * 100;
[self setupTimer];
[self setupPageControl];
[self.mainView reloadData];
}
- (void)setImageURLsGroup:(NSArray *)imageURLsGroup
{
_imageURLsGroup = imageURLsGroup;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:imageURLsGroup.count];
for (int i = 0; i < imageURLsGroup.count; i++) {
UIImage *image = [[UIImage alloc] init];
[images addObject:image];
}
self.imagesGroup = images;
[self loadImageWithImageURLsGroup:imageURLsGroup];
}
- (void)setLocalizationImagesGroup:(NSArray *)localizationImagesGroup
{
_localizationImagesGroup = localizationImagesGroup;
self.imagesGroup = [NSMutableArray arrayWithArray:localizationImagesGroup];
}
- (void)loadImageWithImageURLsGroup:(NSArray *)imageURLsGroup
{
for (int i = 0; i < imageURLsGroup.count; i++) {
[self loadImageAtIndex:i];
}
}
- (void)loadImageAtIndex:(NSInteger)index
{
NSURL *url = self.imageURLsGroup[index];
// 如果有缓存,直接加载缓存
NSData *data = [NSData getDataCacheWithIdentifier:url.absoluteString];
if (data) {
[self.imagesGroup setObject:[UIImage imageWithData:data] atIndexedSubscript:index];
} else {
// 网络加载图片并缓存图片
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url]
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
if (!connectionError) {
UIImage *image = [UIImage imageWithData:data];
if (!image) return; // 防止错误数据导致崩溃
[self.imagesGroup setObject:image atIndexedSubscript:index];
dispatch_async(dispatch_get_main_queue(), ^{
if (index == 0) {
[self.mainView reloadData];
}
});
[data saveDataCacheWithIdentifier:url.absoluteString];
} else { // 加载数据失败
static int repeat = 0;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (repeat > 10) return;
[self loadImageAtIndex:index];
repeat++;
});
}
}
];
}
}
- (void)setupPageControl
{
if (_pageControl) [_pageControl removeFromSuperview]; // 重新加载数据时调整
TAPageControl *pageControl = [[TAPageControl alloc] init];
pageControl.numberOfPages = self.imagesGroup.count;
pageControl.dotColor = self.dotColor;
[self addSubview:pageControl];
_pageControl = pageControl;
}
- (void)automaticScroll
{
if (0 == _totalItemsCount) return;
int currentIndex = _mainView.contentOffset.x / _flowLayout.itemSize.width;
int targetIndex = currentIndex + 1;
if (targetIndex == _totalItemsCount) {
targetIndex = _totalItemsCount * 0.5;
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
- (void)setupTimer
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
_timer = timer;
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)layoutSubviews
{
[super layoutSubviews];
_mainView.frame = self.bounds;
if (_mainView.contentOffset.x == 0 && _totalItemsCount) {
[_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_totalItemsCount * 0.5 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}
CGSize size = [_pageControl sizeForNumberOfPages:self.imagesGroup.count];
CGFloat x = (self.sd_width - size.width) * 0.5;
if (self.pageControlAliment == SDCycleScrollViewPageContolAlimentRight) {
x = self.mainView.sd_width - size.width - 10;
}
CGFloat y = self.mainView.sd_height - size.height - 10;
_pageControl.frame = CGRectMake(x, y, size.width, size.height);
[_pageControl sizeToFit];
}
//解决当父View释放时,当前视图因为被Timer强引用而不能释放的问题
- (void)willMoveToSuperview:(UIView *)newSuperview
{
if (!newSuperview) {
[_timer invalidate];
_timer = nil;
}
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return _totalItemsCount;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SDCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
long itemIndex = indexPath.item % self.imagesGroup.count;
cell.imageView.image = self.imagesGroup[itemIndex];
if (_titlesGroup.count) {
cell.title = _titlesGroup[itemIndex];
}
if (!cell.hasConfigured) {
cell.titleLabelBackgroundColor = self.titleLabelBackgroundColor;
cell.titleLabelHeight = self.titleLabelHeight;
cell.titleLabelTextColor = self.titleLabelTextColor;
cell.titleLabelTextFont = self.titleLabelTextFont;
cell.hasConfigured = YES;
}
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:@selector(cycleScrollView:didSelectItemAtIndex:)]) {
[self.delegate cycleScrollView:self didSelectItemAtIndex:indexPath.item % self.imagesGroup.count];
}
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
int itemIndex = (scrollView.contentOffset.x + self.mainView.sd_width * 0.5) / self.mainView.sd_width;
if (!self.imagesGroup.count) return; // 解决清除timer时偶尔会出现的问题
int indexOnPageControl = itemIndex % self.imagesGroup.count;
_pageControl.currentPage = indexOnPageControl;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[_timer invalidate];
_timer = nil;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
[self setupTimer];
}
@end