• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - ScrollView和ImageView-多次旋转设备后图像未居中

[复制链接]
菜鸟教程小白 发表于 2022-12-13 09:02:43 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我的应用程序中有一个带有三个视图的segmentedControl,其中一个是scrollView,它的工作原理类似于一种没有缩放的画廊,其pageControlimageView居中。

层次结构就像

->分段控件(3个视图):descriptionView,imageTabView,shareView
----> imagesTabView(UIView)
------> scrollView
------> imageView
----> pageControl

当设备是纵向或横向时,imageView图像会正确显示,它们将居中,并且滚动效果非常好。

唯一的问题是,当您再次打开设备时,如果图像“在中间”(例如3的第2或6的第3),则显示为偏心,向左或向右移动,并稍微滑动一下它返回到中心,而如果图像是第一个或最后一个,则它可以正常工作。

我在S.O.上看过这里在各种线程上,尝试将contentView设置为scrollView的子视图,然后将imageView添加为contentView的子视图,但是没有用,尝试将imageView附加到scrollView的底部或右侧,但没有用。

我觉得我距离实现自己的目标还很远,唯一的问题是我无法理解为什么它没有居中。

viewWillLayoutSubviews中,我指定了contentSize,以便在旋转时正确设置其大小,例如

-(void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.scrollView.contentSize = CGSizeMake (self.scrollView.frame.size.width * photosArray.count, 1);
}

这是初始化pageControl,scrollView和imageView的方法:
-(void)configureImageTab{
    pageControl = [UIPageControl new];
    [pageControl addTarget:self actionselector(changePage) forControlEvents:UIControlEventValueChanged];
    pageControl.translatesAutoresizingMaskIntoConstraints = NO;

    //Don't show pageControl when there are no photos
    if (photosURL.count == 0)
        pageControl.hidden = YES;

    //Configuring scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.imageSegmentView.frame.size.width, self.imageSegmentView.frame.size.height-pageControl.frame.size.height)];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;

    //... Code cut - adding remote images to fetch to array

    //Actual setup -> scrollView adding imageView as subview with all the images
    for (int i =0; i< photosArray.count; i++){
        CGRect frame;
        frame.origin.x = self.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.scrollView.frame.size;

        //imageView setup
        imageView = [[UIImageView alloc]initWithFrame:frame];
        imageView.backgroundColor = [UIColor clearColor];
        imageView.clipsToBounds = YES;
        imageView.userInteractionEnabled = YES;
        imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        imageView.translatesAutoresizingMaskIntoConstraints = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFit;

        //Setting images urls
        [imageView setImageWithURL:[NSURL URLWithString:[photosArray objectAtIndex:i]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        //Error handling 
            }
        }usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

        //Adding gesture recognizer to scrollView and imageView as subview
        [self.scrollView addGestureRecognizer:singleTap];
        [self.scrollView addSubview:imageView];
    }

    //Setting the contentSize
    pageControl.numberOfPages = [photosURL count];

    [self.imageSegmentView addSubview:self.scrollView];
    [self.imageSegmentView addSubview:pageControl];

    //Constraints
    NSDictionary *views = @{@"pageControl" : pageControl, @"scrollView" : self.scrollView};

    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|-0-[pageControl]-0-|" options:0 metrics:nil views:views]];
    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"V:|[scrollView]-1-[pageControl]-1-|" options:0 metrics:nil views:views]];
    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|[scrollView]|" options:0 metrics:nil views:views]];

    [pageControl addConstraint:[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.imageSegmentView attribute:NSLayoutAttributeHeight multiplier:0 constant:30]];
}

#pragma mark - scrollView delegate -

-(void)scrollViewDidScrollUIScrollView *)sView{
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor ((self.scrollView.contentOffset.x - pageWidth /2) /pageWidth) +1;
    self.pageControl.currentPage = page;
}

-(IBAction)changePage {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;
    [self.scrollView scrollRectToVisible:frame animated:YES];
}

-(void)scrollViewWillBeginDraggingUIScrollView *)scrollView{
    pageControlBeingUsed = NO;
}

-(void)scrollViewDidEndDeceleratingUIScrollView *)scrollView{
    pageControlBeingUsed = NO;
}

需要说明的一点是:imageView使用的是autoresizingMask:如果不这样做,它将无法正确显示图像。

我的猜测是,scrollView委托中可能需要修复一些问题,但我不太确定。

任何建议表示赞赏!

编辑

我注意到在浏览用户的图片然后打开设备时,Twitter应用程序中也会发生相同的错误。

编辑TL; DR的2

基本上,假设我在带有分页的水平scrollView中有3张图像。

我在第一张照片上将设备从“肖像”转换为“风景”,并在正确位置居中显示在自己的位置。

我移到下一张照片,居中显示,然后再次将设备转到肖像。照片未正确对齐,未居中

实际上,当设备旋转多次时,第一个和最后一个图像会居中显示。其他不居中

编辑3

我提取了一些行,并做了一个sample project来演示我遇到的问题。我想contentSize肯定有问题。



Best Answer-推荐答案


我们可以通过在界面将要旋转时记录当前页面,然后在系统旋转后适当地设置滚动视图的contentOffset来解决您正在谈论的特定错误(滚动视图在滚动视图后未对齐页面边界)已更新滚动视图的边界大小。让我们添加一个pageNumberPriorToRotation实例变量:

@implementation ViewController {
    CGFloat pageNumberPriorToRotation;
}

然后,在界面即将旋转时进行设置:
- (void)willRotateToInterfaceOrientationUIInterfaceOrientation)toInterfaceOrientation durationNSTimeInterval)duration {
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self setPageNumberPriorToRotation];
}

- (void)setPageNumberPriorToRotation {
    CGRect bounds = self.scrollView.bounds;
    static const int kNumberOfImages = 3;
    pageNumberPriorToRotation = fmin(round(bounds.origin.x / bounds.size.width),
        kNumberOfImages - 1);
}

我们使用它来设置界面旋转期间滚动视图的contentOffset:
-(void)willAnimateRotationToInterfaceOrientationUIInterfaceOrientation)toInterfaceOrientation durationNSTimeInterval)duration{
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self updateScrollViewLayout];
}

- (void)updateScrollViewLayout {
    CGRect bounds = self.scrollView.bounds;
    bounds.origin.x = bounds.size.width * pageNumberPriorToRotation;
    self.scrollView.bounds = bounds;
}

这可以解决您的主要抱怨:旋转后,滚动视图将始终与页面视图边界对齐。

然而…

滚动视图交互还存在其他一些问题。在横向方向上,我无法滚动到第三张图像。旋转到风景并回到肖像后,我可以滚动到空白的第四页。这些问题大概就是您所说的“contentSize肯定存在某些问题”的意思。

此外,您的代码有很多问题。它使用一些过时的样式,例如为属性显式声明实例变量并将实例变量放在头文件中。它还患有Massive View Controller。它确实可以用现代风格重写,并使用UITabBarControllerUIPageViewController等功能。

无论如何,您可能既没有时间也没有时间去做那么多工作,所以我将向您展示如何解决contentSize问题并同时缩小VC的范围。

我将创建一个名为UIScrollViewImageScrollView子类。您给了我一组图像,我将负责设置其子视图并在旋转后与页面边界对齐。这是我的头文件:
ImageScrollView.h
#import <UIKit/UIKit.h>

@interface ImageScrollView : UIScrollView

@property (nonatomic, copy) NSArray *images;

@end

为了实现这一点,我需要一些实例变量:
ImageScrollView.m
#import "ImageScrollView.h"
#import <tgmath.h>

@implementation ImageScrollView {
    NSMutableArray *imageSubviews;
    CGSize priorSize;
    CGFloat pageNumber;
    BOOL needsToSyncSubviewsWithImages : 1;
}

无论如何,首先我将实现 public API,它只是images属性:
#pragma mark - Public API

@synthesize images = _images;

- (void)setImagesNSArray *)images {
    _images = [images copy];
    needsToSyncSubviewsWithImages = YES;
}

请注意,当您设置images数组时,我不要立即创建子视图。现在,我只设置needsToSyncSubviewsWithImages标志,这样我就知道在布局阶段要这样做。
#pragma mark - UIView overrides

接下来,我需要重写layoutSubviews,以便可以在布局阶段进行实际工作。如果我的layoutSubviews数组已更改,或者我的subviews已更改,则系统会在布局阶段向我发送bounds

因为我是滚动视图,并且因为滚动视图的contentOffset实际上只是其bounds.origin的别名,所以系统在每次滚动视图滚动时都会向我发送layoutSubviews。因此,我想小心地仅在layoutSubviews中执行必要的工作。
- (void)layoutSubviews {

我要做的第一件事是调用super,它可以让自动布局工作(如果正在使用)并更新我的滚动指示器(如果它们可见)。
    [super layoutSubviews];

接下来,如果有新图像,则设置显示它们的子视图。
    if (needsToSyncSubviewsWithImages) {
        [self syncSubviewsWithImages];
    }

接下来,如果我设置了新的子视图,或者更改了大小,则将子视图的框架布置为新的大小,并与页面边界对齐。
    if (needsToSyncSubviewsWithImages || !CGSizeEqualToSize(self.bounds.size, priorSize)) {
        [self layoutForNewSize];
    }

最后,我更新我的状态。
    needsToSyncSubviewsWithImages = NO;
    priorSize = self.bounds.size;
    [self updatePageNumber];
}

当然,我将所有实际工作委托给了辅助方法,因此现在我需要实现这些方法。
#pragma mark - Implementation details

要将子视图与图像同步,我需要做三件事。我需要确保我实际上已经分配了imageSubviews数组,我需要确保每个图像都在子视图中,并且我需要确保我没有任何额外的图像子视图(以防我的images数组变小了) )。
- (void)syncSubviewsWithImages {
    [self ensureImageSubviewsArrayExists];
    [self putImagesInSubviews];
    [self removeExtraSubviews];
}

- (void)ensureImageSubviewsArrayExists {
    if (imageSubviews == nil) {
        imageSubviews = [NSMutableArray arrayWithCapacity:self.images.count];
    }
}

- (void)putImagesInSubviews {
    [self.images enumerateObjectsUsingBlock:^(id obj, NSUInteger i, BOOL *stop) {
        [self putImagebj inSubviewAtIndex:i];
    }];
}

- (void)removeExtraSubviews {
    while (imageSubviews.count > self.images.count) {
        [imageSubviews.lastObject removeFromSuperview];
        [imageSubviews removeLastObject];
    }
}

- (void)putImageUIImage *)image inSubviewAtIndexNSUInteger)i {
    UIImageView *imageView = [self imageViewAtIndex:i];
    imageView.image = image;
}

当我想获取索引的图像视图时,可能会发现实际上尚未创建足够的子视图,因此我按需创建了它们:
- (UIImageView *)imageViewAtIndex:(NSUInteger)i {
    while (i >= imageSubviews.count) {
        UIView *view = [[UIImageView alloc] init];
        view.contentMode = UIViewContentModeScaleAspectFit;
        view.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
        [self addSubview:view];
        [imageSubviews addObject:view];
    }
    return imageSubviews[i];
}

请注意,我已经设置了autoresizingMask,以使自动调整大小实际上不会修改我的子视图框架。相反,我将“手动”布置它们。

好的,现在我需要实现设置子视图框架并在尺寸改变时对齐页面边界的方法。
- (void)layoutForNewSize {
    [self setSubviewFramesAndContentSize];
    [self alignToNearestPage];
}

设置子视图框架需要在它们上循环,从左到右布置它们。布置完最后一个后,我知道了contentSize。注意,我只需要循环imageSubviews,而不是self.subviews,因为self.subviews也包含滚动指示器。
- (void)setSubviewFramesAndContentSize {
    CGRect frame = self.bounds;
    frame.origin = CGPointZero;
    for (UIView *subview in imageSubviews) {
        subview.frame = frame;
        frame.origin.x += frame.size.width;
    }
    self.contentSize = CGSizeMake(frame.origin.x, frame.size.height);
}

为了与最近的页面对齐,我根据最近的已知页面编号和新尺寸设置了contentOffset
- (void)alignToNearestPage {
    self.contentOffset = CGPointMake(pageNumber * self.bounds.size.width, 0);
}

最后,每次滚动时我都需要更新页码,以便轮换使用:
- (void)updatePageNumber {
    // Note that self.contentOffset == self.bounds.origin.
    CGRect bounds = self.bounds;
    pageNumber = fmin(round(bounds.origin.x / bounds.size.width), self.images.count - 1);
}

@end

现在,您可以更新ViewController以使用ImageScrollView。这主要涉及撕碎东西:
-(void)configureImageTab{
    //Page control
    pageControl = [UIPageControl new];
    pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    [pageControl addTarget:self actionselector(changePage) forControlEvents:UIControlEventValueChanged];
    pageControl.translatesAutoresizingMaskIntoConstraints = NO;


    //Configuring scrollView
    self.scrollView = [[ImageScrollView alloc] initWithFrame:CGRectMake(0, 0, self.imageSegmentView.frame.size.width, self.imageSegmentView.frame.size.height-pageControl.frame.size.height)];
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;

    //Adding imageURLS to array
    photos = @[ [UIImage imageNamed"createBootableUSBInstallDrive1"], [UIImage imageNamed"createBootableUSBInstallDrive2"], [UIImage imageNamed"createBootableUSBInstallDrive3"]];
    self.scrollView.images = photos;

    pageControl.numberOfPages = [photos count];

    [self.imageSegmentView addSubview:self.scrollView];
    [self.imageSegmentView addSubview:pageControl];


    NSDictionary *views = @{@"pageControl" : pageControl, @"scrollView" : self.scrollView};

    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|-0-[pageControl]-0-|" options:0 metrics:nil views:views]];
    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat"H:|[scrollView]|" options:0 metrics:nil views:views]];

    [self.imageSegmentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[scrollView]-1-[pageControl]-1-|" options:0 metrics:nil views:views]];

    [pageControl addConstraint:[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.imageSegmentView attribute:NSLayoutAttributeHeight multiplier:0 constant:30]];
}

您还需要在头文件中将scrollView的声明类型更改为ImageScrollView。您可以完全消除viewWillLayoutSubviewswillRotateToInterfaceOrientation:duration:willAnimateRotationToInterfaceOrientation:duration:方法。

我已经将您的测试项目的修改后的版本上传到this github repository

关于ios - ScrollView和ImageView-多次旋转设备后图像未居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25920880/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap