UIScrollView如何与StoryBoard一起使用并显示不同的UIViewControllers?

时间:2012-01-22 13:54:44

标签: ios5 uiscrollview uilabel storyboard

我有一个StoryBoard。在那里有一个UIViewController - 我已经把UIScrollView和UIPageControl。在每个页面上(比如我有3个)我试图加载一个UIViewController(显示不同的标签和表值)。

问题 - 我可以加载所有内容,但标签和表格不可见。当我尝试更改每个页面的背景颜色时 - 它确实会发生变化。我已经研究了各种帖子和代码,但似乎没有任何工作/使用StoryBoard显示UIScrollView(使用UIViewController显示标签和表格)。

我可以通过加载单独的XIB文件来执行此操作,但随后整个segue被中断。 请参阅下面的代码。

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];

//ScrollView and PageControl

// Create view controllers placeholder array
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfPages; i++) 
{
    [controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;    
// Set Scroll View
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * numberOfPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self; 
// Set Page Control
pageControl.numberOfPages = numberOfPages;
pageControl.currentPage = 0;
// Load the visible and next page
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
if (pageControlUsed)
{
    // To know if scroll is valid - from Page Control
    return;
}

// Changes Page Control indicator
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;

// Load the visible, previous and next pages
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}

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

- (void)loadScrollViewWithPage:(int)page
{
if (page < 0) return;
if (page >= numberOfPages) return;

// Load new Controller
ReportsDetailViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) 
{
    controller = [[ReportsDetailViewController alloc] init];
    controller.pageNumber = [NSNumber numberWithInt:page];
    [viewControllers replaceObjectAtIndex:page withObject:controller];
}   
if (nil == controller.view.superview) 
{
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    controller.view.frame = frame;
    [scrollView addSubview:controller.view];
}
}

1 个答案:

答案 0 :(得分:3)

尝试创建这样的ViewControllers:

YourViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"YourViewController"];

您可以在属性检查器中设置视图控制器的标识符。

我今天遇到了同样的问题,这对我来说很有用。