使用页面控件在 UIScrollView 中以横向模式无法正确加载图像

Image not loading properly in landscape mode in UIScrollView with Page Control

我需要能够在横向和纵向模式下为所有设备正确加载图像。 在加载图像时我还需要适当的内存管理。现在我的代码一次加载所有图像,但将来我会添加更多图像,因此需要优化的内存解决方案。

- (void)viewDidLoad {
[super viewDidLoad];

self.automaticallyAdjustsScrollViewInsets = NO;
self.navigationController.navigationBarHidden = YES;

_photoArray = [NSArray arrayWithObjects:@"image1.jpg",@"image2.jpg",@"image3.jpg",@"image4.jpg",@"image5.jpg",@"image6.jpg",@"image7.jpg",@"image8.jpg",@"image9.jpg", nil];

self.pageControl.numberOfPages = _photoArray.count;

CGSize screen = [[UIScreen mainScreen] bounds].size;

for(int i = 0; i < _photoArray.count; i++)
{
    self.subScrollView = [[UIScrollView alloc] init];
    self.subScrollView.frame = CGRectMake((i * screen.width), 0, screen.width, screen.height);
    [self.subScrollView setMinimumZoomScale:1];
    [self.subScrollView setZoomScale:1];
    [self.subScrollView setMaximumZoomScale:3];
    self.subScrollView.delegate = self;


    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:_photoArray[i]]];
    imgView.frame = self.subScrollView.bounds;
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    imgView.clipsToBounds = YES;
    imgView.tag = i;

    [self.subScrollView addSubview:imgView];

    [_scrView addSubview:self.subScrollView];

    if(i == _photoArray.count-1)
        _scrView.contentSize = CGSizeMake(self.subScrollView.frame.origin.x + self.subScrollView.frame.size.width, screen.height);
}
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return [scrollView viewWithTag:self.pageControl.currentPage];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//page control
CGFloat pageWidth = self.scrView.frame.size.width;
self.pageControl.currentPage = (self.scrView.contentOffset.x +pageWidth/2)/pageWidth;
}

我认为优化内存的最佳选择是使用 UICollectionView 而不是 UIScrollView。您也可以将 UIPageControl 与 UICollectionView 一起使用。

    - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
        return 1;
    }

    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
        return self.imagesArray.count;
    }

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        UICollectionViewCell *cell == [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"image%d.jpg",indexPath.row]]];
        [cell.addSubView:image];
        return cell;
    }