我之前做过一个使用UIScrollView和Paging的项目,但是对于这个新项目,我一直在讨论这个问题而无法让它运转起来。我认为问题可能在于AutoLayout。起初我无法使分页动作均匀工作,直到我意识到所有初始化都必须在viewDidAppear而不是ViewDidLoad中完成。
既然我已经完成了分页操作,那么subView就不会加载!它只是将我在Storyboard中设置的当前视图推开,只显示空白背景。
请注意,此处的代码与我之前的项目几乎相同,但我无法显示第二个视图(第2页)。
以下是一些代码:
- (void)viewDidAppear:(BOOL)animated{
self.scrollView.delegate = self;
// view controllers are created lazily
// in the meantime, load the array with placeholders which will be replaced on demand
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++)
{
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, (scrollView.frame.size.height - 50));
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
//
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page
{
if (page <= 0)
return;
if (page >= kNumberOfPages)
return;
PageOneViewController *controller = [viewControllers objectAtIndex:1];
if ((NSNull *)controller == [NSNull null])
{
if(page == 1)
{
controller = [[PageOneViewController alloc] initWithRequestNumber: @"100" forID:self.idNumberFromLogin];
[viewControllers replaceObjectAtIndex:page withObject:controller];
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * 1;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
}
在PageOneViewController
中 - (id)initWithRequestNumber:(NSString *)requestID forID: (NSString *) employeeID
{
if (self = [super initWithNibName:@"OpenRequestCommView" bundle:nil])
{
}
return self;
}
答案 0 :(得分:2)
您可以在故事板上启用自动布局。
您可以通过选择故事板中的文件检查器并取消选中“使用Autolayout”来禁用自动布局。
答案 1 :(得分:0)
您需要将此代码放在.m
中#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
后
更新您的代码
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (IS_WIDESCREEN) {
self.meuScroll.frame = CGRectMake(0, 0, 320, 468);
} else {
self.meuScroll.frame = CGRectMake(0, 0, 320, 380);
}
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if (IS_WIDESCREEN) {
self.meuScroll.contentSize = CGSizeMake(320, 468);
} else {
self.meuScroll.contentSize = CGSizeMake(320, 380);
}
}
答案 2 :(得分:0)
上面问题中的代码是基于使用Apple提供的UIScrollView进行分页的示例代码构建的。我为我的应用程序使用了相同的代码,并花了几个小时来完成教程,堆栈溢出问题和示例代码,但没有什么可以通过其scrollview修复自动布局问题。事实证明,您只需要在方法中添加一行代码,该方法将scrollView作为控制器的视图返回。 (这是示例代码中的PhoneContentController类)
- (UIView *)view
{
[self.scrollView setTranslatesAutoresizingMaskIntoConstraints:YES];
return self.scrollView;
}