项目中会需要一些循环滚动的视图,而这些资源我们并不知道有多少或者有很多图片需要循环显示,这样如果设置很多imageview势必会浪费很多内存.所以,博主写了一个小Demo希望可以给大家一点启发.
实现的思想大致是:设置3个view放在scrollview上,通过改变view的fream和scrollview的contentoffset来实现循环滚动,好了,不多说,贴代码..~~
#define SC_Width 200
#define SC_Hight 300
@interface JLRootViewController ()<UIScrollViewDelegate>
@end
@implementation JLRootViewController
{
UIView *view1;
UIView *view2;
UIView *view3;
UIScrollView *_scroll;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self createUI];
}
- (void)createUI
{
[self.view setBackgroundColor:[UIColor whiteColor]];
_scroll = [[UIScrollView alloc] init];
[_scroll setBounds:CGRectMake(0, 0, SC_Width, SC_Hight)];
[_scroll setCenter:self.view.center];
[_scroll setDelegate:self];
_scroll.contentSize = CGSizeMake(SC_Width*3,SC_Hight);
// 这个属性设置成yes,viewcontroller的automaticallyAdjustsScrollViewInsets属性会自动调整scrollview的内容,此处不让其自动调整
self.automaticallyAdjustsScrollViewInsets = NO;
_scroll.pagingEnabled = YES;
[self.view addSubview:_scroll];
// 三个view
view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SC_Width, SC_Hight)];
[view1 setBackgroundColor:[UIColor greenColor]];
view2 = [[UIView alloc] initWithFrame:CGRectMake(SC_Width, 0, SC_Width, SC_Hight)];
[view2 setBackgroundColor:[UIColor blueColor]];
view3 = [[UIView alloc] initWithFrame:CGRectMake(SC_Width*2, 0, SC_Width, SC_Hight)];
[view3 setBackgroundColor:[UIColor purpleColor]];
// 添加到self.view
[_scroll addSubview:view1];
[_scroll addSubview:view2];
[_scroll addSubview:view3];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// 左滑
if (scrollView.contentOffset.x >= SC_Width*2) {
// 将三个view的fream的x-SC_Width,如果fream超出范围则加到最后边
view1.frame = CGRectMake(view1.frame.origin.x >= SC_Width ? view1.frame.origin.x-SC_Width : SC_Width*2, 0, SC_Width, SC_Hight);
view2.frame = CGRectMake(view2.frame.origin.x >= SC_Width ? view2.frame.origin.x-SC_Width :SC_Width*2, 0, SC_Width, SC_Hight);
view3.frame = CGRectMake(view3.frame.origin.x >= SC_Width ? view3.frame.origin.x-SC_Width :SC_Width*2, 0, SC_Width, SC_Hight);
// 将中间的view显示在scroll上
scrollView.contentOffset = CGPointMake(SC_Width, 0);
}
// 右滑
if (scrollView.contentOffset.x <=0) {
// 将三个view的fream的x+SC_Width,如果fream超出范围则加到最前边
view1.frame = CGRectMake(view1.frame.origin.x >= SC_Width*2 ? 0: view1.frame.origin.x+SC_Width, 0, SC_Width, SC_Hight);
view2.frame = CGRectMake(view2.frame.origin.x >= SC_Width*2 ? 0 : view2.frame.origin.x+SC_Width, 0, SC_Width, SC_Hight);
view3.frame = CGRectMake(view3.frame.origin.x >= SC_Width*2 ? 0 : view3.frame.origin.x+SC_Width, 0, SC_Width, SC_Hight);
// 将中间的view显示在scroll上
scrollView.contentOffset = CGPointMake(SC_Width, 0);
}
}
以上的代码就可以实现循环滚动的问题,而且不需要创建多个view.