用scrollview实现动态加载并支持横竖屏

来源:互联网 发布:大气环境防护距离软件 编辑:程序博客网 时间:2024/06/08 06:16

        刚开始接触IOS,公司就让我用scrollview实现动态加载并支持横竖屏,但是我连scrollview原理是什么都不大懂。然后就去网上找资料,看代码。不过网上的人都是牛人啊,写的不全,代码也很复杂。我在code4中下载了个无限加载的例子,感觉理解的可以之后开始改。改着改着就出问题了:页面不停刷新,屏幕翻转的时候图片会重复加载,而且有时候系统不调用我在willAnimateRotationToInterfaceOrientation中写的方法,麻烦死了。

        上面是我那段时间想问题想错了写的草稿。我改了人家的逻辑代码,而且自己对scrollview还不完全了解,所以才导致屏幕闪动。下面是闪动和不闪动的代码,给自己做个记录。

闪动的主要代码:

- (void) vertical{

    [self getImagesWithCurpage:currentPage];  //根据当前页面重新设置curImages中的

    

    

    CGRect imageViewRect =self.view.bounds;

    for (int i=0;i<5; i++) {

        NSString *string = [curImages objectAtIndex:i ];

        UIImage *image = [UIImage imageNamed:string];

        UIImageView *imageView = [[UIImageView alloc]initWithImage:image];

            

        imageView.frame = CGRectOffset(imageView.frame, imageViewRect.size.width * i, 0);

        

        [self.myScrollviewaddSubview:imageView];

    }

    self.myScrollview.contentSize = CGSizeMake(self.view.bounds.size.width * 5.0f, self.view.bounds.size.height);

    position = myScrollview.contentOffset.x / (self.view.bounds.size.width);//计算在ScrollView当前的页码


    [myScrollview setContentOffset:CGPointMake(imageViewRect.size.width*position,0)];

    

}

改了之后的代码:


- (void) vertical{

    [selfgetImagesWithCurpageV :currentPage];  //根据当前页面重新设置curImages中的值

    

    

    for (int i=0; i<3; i++) {

        NSString *string = [curImagesobjectAtIndex:i ];

        UIImage *image = [UIImageimageNamed:string];

        UIImageView *imageView = [[UIImageViewalloc]initWithImage:image];

        

        CGRect imageViewFrame = self.myScrollview.bounds;

        imageViewFrame.origin.x = i *self.myScrollview.bounds.size.width;

        imageView.frame = imageViewFrame;

        

        [self.myScrollviewaddSubview:imageView];

    }

    self.myScrollview.contentSize =CGSizeMake(self.view.bounds.size.width *3, self.myScrollview.bounds.size.height);

    

    [myScrollviewsetContentOffset:CGPointMake(self.myScrollview.bounds.size.width,0)];

    

}

把红色部分删掉就可以了。本来人家代码中就没有的,我为了支持横竖屏转换自己加上去的,横竖屏做出来了,但是会出现闪动。当初看了很多次都不知道自己的问题在什么地方,还是自己起初的思路有问题啊!

转屏的时候,横屏和竖屏要存在一张相同的图片(横屏每次显示2张,竖屏1张),其实没必要算在scrollView中的偏移值,只要根据当前的页面进行重新绘制就可以了。


原创粉丝点击