gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:42:20 26 4
gpt4 key购买 nike

我的应用程序中有一个带有三个视图的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 action:@selector(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)scrollViewDidScroll:(UIScrollView *)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)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
pageControlBeingUsed = NO;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
pageControlBeingUsed = NO;
}

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

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

任何建议表示赞赏!

编辑

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

编辑TL; DR的2

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

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

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

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

编辑3

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

最佳答案

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

@implementation ViewController {
CGFloat pageNumberPriorToRotation;
}

然后,在界面即将旋转时进行设置:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)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)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)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)setImages:(NSArray *)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 putImage:obj inSubviewAtIndex:i];
}];
}

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

- (void)putImage:(UIImage *)image inSubviewAtIndex:(NSUInteger)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 action:@selector(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com