聲明必要的屬性
//保存可見的視圖
@property (nonatomic, strong) NSMutableSet * visibleImageViews;
//保存可重用的視圖
@property (nonatomic, strong) NSMutableSet * reusedImageViews;
//滾動視圖
@property (nonatomic, weak) UIScrollView * scrollView;
//所有的圖片
@property (nonatomic, strong) NSArray * imageNames;
創(chuàng)建UIScrollView
UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
scrollView.pagingEnabled = YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.contentSize = CGSizeMake(self.imageNames.count*self.view.bounds.size.width, self.view.bounds.size.height);
[self.view addSubview:scrollView];
self.scrollView = scrollView;
//顯示第一張圖片
[self showImageViewAtIndex:0];
顯示第一張圖片
//顯示一個圖片的view
- (void)showImageViewAtIndex:(NSInteger)index
{
//先從復(fù)用池中找imageview
UIImageView * imageView = [self.reusedImageViews anyObject];
if (!imageView) {//沒有就創(chuàng)建一個
imageView = [[UIImageView alloc]init];
imageView.contentMode = UIViewContentModeScaleAspectFit;
}else{//有的話就 把imageview移除
[self.reusedImageViews removeObject:imageView];
}
//在這里可以配置imageview
CGRect bounds = self.scrollView.bounds;
CGRect imageViewFrame = bounds;
imageViewFrame.origin.x = CGRectGetWidth(bounds) * index;
imageView.tag = index;
imageView.frame = imageViewFrame;
imageView.image = [UIImage imageNamed:self.imageNames[index]];
//把剛才從reusedImageViews移除的對象添加到visibleImageViews對象中
[self.visibleImageViews addObject:imageView];
//顯示到scrollow上
[self.scrollView addSubview:imageView];
}
滑動顯示更多圖片
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self showImages];
}
- (void)showImages
{
//獲取當前顯示范圍內(nèi)的圖片的索引
CGRect bounds = self.scrollView.bounds;
CGFloat minX = CGRectGetMinX(bounds);
CGFloat maxX = CGRectGetMaxX(bounds);
CGFloat width = CGRectGetWidth(bounds);
//第一個索引
NSInteger firstIndex = (NSInteger)floor(minX / width);
//最后一個索引
NSInteger lastIndex = (NSInteger)floor(maxX / width);
//處理越界情況
if (firstIndex < 0) firstIndex = 0;
if (lastIndex >= self.imageNames.count) lastIndex = self.imageNames.count - 1;
//回收不再顯示的imageview
NSInteger imageViewIndex = 0;
for (UIImageView * imageView in self.visibleImageViews)
{
imageViewIndex = imageView.tag;
//不在顯示范圍內(nèi)的
if (imageViewIndex < firstIndex || imageViewIndex > lastIndex)
{
//添加到復(fù)用池中
[self.reusedImageViews addObject:imageView];
[imageView removeFromSuperview];
}
}
//取出復(fù)用池中的圖片
[self.visibleImageViews minusSet:self.reusedImageViews];
//是否需要顯示心的視圖
for (NSInteger index = firstIndex; index <= lastIndex; index++)
{
BOOL isShow = NO;
//遍歷可見數(shù)據(jù)的對象
for (UIImageView * imageView in self.visibleImageViews)
{
if (imageView.tag == index)
{
isShow = YES;
}
}
if (!isShow)
{
[self showImageViewAtIndex:index];
}
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者