Как создать UIScrollview, где он показывает часть представления с обеих сторон? - PullRequest
0 голосов
/ 26 августа 2011

Я пытаюсь создать UIScrollView, где он будет отображать часть представлений, содержащихся в UIScrollView с обеих сторон.

Вот изображение;

Example of UIScrollview

На рисунке показана серая область, которая является родительским или основным видом. фиолетовый область - это UIScrollView.Область white - это изображение, которое содержит изображение поля, готовый заголовок и кнопку быстрого запуска.

Проблема, с которой я столкнулся, заключается в том, что эта область white занимают все пространство, и на экране нет визуальной индикации, которую можно даже прокрутить, не говоря уже о том, что есть больше контента.

В идеале, я хочу, чтобы было несколько белые подпредставления в UIScrollView, так что вы можете увидеть часть каждого подпредставления с любой стороны, примерно так:

concept

В этой концепции вы увидите, чтоявляется частью отрезка подпредставления, но больше всего вы увидите несколько подпредставлений в UIScrollView.

Подвид (тот, который содержится в разделе white ) - 75(ширина) x 160 (высота).

Однако я не могу заставить это работать.Я попытался установить clipToBounds как да, так и нет, и я попытался принудительно увеличить размер содержимого;оба из которых дают неожиданные результаты.

Как мне сделать так, чтобы в UIScrollView отображалось более 1 UIView или части UIViews в UIScrollView?

Большое спасибо.

Вот мой код:

// Code follows
- (void)viewDidLoad
{
    // Scrollview
    int recordsFound = 6; // 6 products
    float scrollViewWidth = (self.scrollView.frame.size.width * recordsFound);
    float scrollViewHeight = (self.scrollView.frame.size.height);

    [self.scrollView setContentSize:CGSizeMake(scrollViewWidth, scrollViewHeight)];    
    [self.scrollView setClipsToBounds:YES];
    [self.scrollView setScrollEnabled:YES];
    [self.scrollView setPagingEnabled:YES];
    [self.scrollView setDirectionalLockEnabled:YES];
    [self.scrollView setUserInteractionEnabled:YES];
    [self.scrollView setShowsHorizontalScrollIndicator:YES];
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    [self.scrollView setScrollEnabled:YES];
    [self.scrollView setDelegate: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 < recordsFound; i++)
    {
        [controllers addObject:[NSNull null]];


    } // next

    //self.scrollView.bounds = CGRectMake(0, 0, 100, scrollView.frame.size.height);


    self.viewControllers = controllers;
    [controllers release];


    [self loadScrollViewWithPage:0];
    [self loadScrollViewWithPage:1];
}



-(void)loadScrollViewWithPage:(int)page
{
    int numberOfRecords = 6;

    if (page < 0)
        return;
    if (page >= numberOfRecords)
        return;

    // replace the placeholder if necessary
    SecondPageVC *controller = [viewControllers objectAtIndex:page];
    if ((NSNull *)controller == [NSNull null])
    {
        controller = [[SecondPageVC alloc] initWithPageNumber:page];        
        [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];

    }


}

-(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 (pageControlBeingUsed)
    {
        // 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;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;

    // 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];

    // A possible optimization would be to unload the views+controllers which are no longer visible
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 
{

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView 
{

}

1 Ответ

0 голосов
/ 04 сентября 2011

Я думаю, что у меня сейчас есть решение, оно не идеальное и нуждается в настройке для темного вида, который вы видите на диаграмме.

У меня все работает для полного просмотра.

То, как я это сделал, было создать вид примерно 210w x 280h и установить его по центру на экране, следующий код позволяет вам увидеть немного каждого вида (разных цветов) с каждой стороны.

Я нашел «ScrollViewPagingExample» на Github ( ссылка )

// Card dimensions = 210 x 280

    // Scrollview    
    [_scrollView setClipsToBounds:NO];
    [_scrollView setPagingEnabled:YES];
    [_scrollView setShowsHorizontalScrollIndicator:NO];
    [_scrollView setAlwaysBounceHorizontal:YES];

    CGFloat contentOffset = 0.0f;


    for (int i = 0; i <5; i++ )
    {
        CGRect someFrame = CGRectMake(contentOffset, 0.0f, _scrollView.frame.size.width, _scrollView.frame.size.height);

        // Create view
        UIView *singleView = [[UIView alloc] initWithFrame:someFrame];

        switch (i) {
            case 0:
                [singleView setBackgroundColor:[UIColor greenColor]];
                break;
            case 1:
                [singleView setBackgroundColor:[UIColor darkGrayColor]];
                break;
            case 2:
                [singleView setBackgroundColor:[UIColor grayColor]];
                break;
            case 3:
                [singleView setBackgroundColor:[UIColor blueColor]];
                break;
            case 4:
                [singleView setBackgroundColor:[UIColor purpleColor]];
                break;
            default:
                //[singleView setBackgroundColor:[UIColor cyanColor]];
                break;
        }


        [singleView setContentMode:UIViewContentModeCenter];

        // Label
        UILabel *lblCardView = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
        [lblCardView setText:[NSString stringWithFormat:@"Card %d", i]]; 
        [lblCardView setTextColor:[UIColor whiteColor]];
        [lblCardView setBackgroundColor:[UIColor clearColor]];

        [singleView addSubview:lblCardView];

        // Add to scrollview        
        [_scrollView addSubview:singleView];

        // Memory management
        [singleView release];
        [lblCardView release];


        // Update contentOffset with padding
        contentOffset += singleView.frame.size.width +35;

        _scrollView.contentSize = CGSizeMake(contentOffset, _scrollView.frame.size.height);

    } // next
...