我的应用程序中有一个带有三个视图的segmentedControl,其中一个是scrollView,它的工作原理类似于一种没有缩放的画廊,其pageControl
和imageView
居中。
层次结构就像
->分段控件(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);
}
-(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;
}
我们可以通过在界面将要旋转时记录当前页面,然后在系统旋转后适当地设置滚动视图的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;
}
UITabBarController
和UIPageViewController
等功能。contentSize
问题并同时缩小VC的范围。UIScrollView
的ImageScrollView
子类。您给了我一组图像,我将负责设置其子视图并在旋转后与页面边界对齐。这是我的头文件: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;
}
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
。您可以完全消除viewWillLayoutSubviews
,willRotateToInterfaceOrientation:duration:
和willAnimateRotationToInterfaceOrientation:duration:
方法。关于ios - ScrollView和ImageView-多次旋转设备后图像未居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25920880/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |