У меня есть ContentViewController, который содержит scrollView.
ScrollView показывает 27 выбираемых элементов на 3 страницах (9 элементов на странице). Это отлично работает.
Когда пользователь нажимает на один из элементов, я перестраиваю массив представления прокрутки, чтобы он содержал все 27 элементов на 27 страницах, по 1 элементу на страницу (используя другой контроллер представления для его отображения). Поэтому, когда вы выбираете предмет, вы получаете подробный вид.
Однако независимо от того, какой элемент выбирает пользователь, второе представление прокрутки загружается пустым. Согласно элементу управления страницы, вид прокрутки находится в нужном месте, но ничего не появляется. Только когда я прокручиваю представление, появляется элемент, но он сбрасывает индекс в начало списка.
Извините за ужасное количество кода, но, возможно, это поможет проиллюстрировать, что происходит не так.
Большое спасибо за любой совет.
- (void)objectSelected: (SelectableObject *)objectSelected {
detailView = TRUE;
self.selectedObject = objectSelected;
[self drawScrollingView];
}
- (void)drawScrollingView {
//Clear out any previous views
[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//Set the background and other interface elements
if (detailView) {
self.background.image = [UIImage imageNamed:@"SelectB.png"];
self.nameField.hidden = FALSE;
pageControl.frame = CGRectMake(0, 380, pageControl.frame.size.width, pageControl.frame.size.height);
numberPages = [self.contentList count];
}
else {
self.background.image = [UIImage imageNamed:@"SelectA1.png"];
pageControl.backgroundColor = [UIColor orangeColor];
//Determine the number of pages
int items = [self.contentList count];
numberPages = items/9;
if (items % 9 != 0)
numberPages++;
}
// 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 < numberPages; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * numberPages, scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = numberPages;
pageControl.hidesForSinglePage = TRUE;
if (!detailView)
pageControl.currentPage = 0;
else
pageControl.currentPage = self.selectedObject.number;
// 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:pageControl.currentPage-1];
[self loadScrollViewWithPage:pageControl.currentPage];
[self loadScrollViewWithPage:pageControl.currentPage+1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0)
return;
if (page >= numberPages)
return;
NSLog(@"PAGE: %i", page);
if (!detailView) {
//Get the subset of objects, depending on the page, and pass it to the controller
//There are 9 objects per page, so page 0 covers 0-8, page 1 covers 9-17, 2 18-26.
//However, there may not be a total of 9
int startIndex = page*9;
int length = 9;
int total = [self.contentList count];
if (startIndex+length > total)
length = total-startIndex;
NSRange theRange;
theRange.location = startIndex;
theRange.length = length;
NSArray *selectionSubset = [self.contentList subarrayWithRange:theRange];
// replace the placeholder if necessary
SelectionScreenViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[SelectionScreenViewController alloc] initWithSet:selectionSubset];
[controller setDelegate:self];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
// add the controller's view to the scroll view
if (controller.view.superview == nil) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
else {
NSLog(@"DETAIL VIEW");
[self.navigationController setToolbarHidden:NO animated:YES];
// replace the placeholder if necessary
SelectionDetailViewController *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSLog(@"controller is NULL");
controller = [[SelectionDetailViewController alloc] initWithObject:[self.contentList objectAtIndex:page]];
[controller setDelegate:self];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
// add the controller's view to the scroll view
if (controller.view.superview == nil) {
NSLog(@"controller superview is NIL");
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
NSLog(@"contentOffset: %g", scrollView.contentOffset);
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if (detailView) { //some other formula here to determine page???
}
pageControl.currentPage = page;
// Set the name
self.selectedObject = [self.contentList objectAtIndex:page];
self.nameField.text = self.selectedObject.name;
NSLog(@"NAME: %@", [[self.contentList objectAtIndex:page] name]);
NSLog(@"ScrollViewDidScrool page: %i", page);
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
}