JohnGray
JohnGray

Reputation: 33

How to Hide and reveal button from scroll view?

I'm Making a game, with level select Ive got 3 levels and 3 views on 3 different controllers

Now I've placed 2 - 1/4 of the button on each side of my scroll view, on on the left and one on the right!

When the user of the game is on level 1 "thats View1" The button on the left needs to be hidden and only show when its on View2 and View 3 - same goes for the button on View3 on the right!

How is this done?

Outlets for those buttons are leftIllusion & rightIllusion

code for UIViews:

@implementation ViewController

@synthesize View1;
@synthesize View2;
@synthesize View3;

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

[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View1"]];
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View2"]];
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"View3"]];

}

code from that imports scroll file .h:

#import "PagerViewController.h"

@interface ViewController : PagerViewController {

}

@property (strong, nonatomic) IBOutlet UIView *View1;
@property (strong, nonatomic) IBOutlet UIView *View2;
@property (strong, nonatomic) IBOutlet UIView *View3;

@end

Upvotes: 0

Views: 1128

Answers (1)

Neil Galiaskarov
Neil Galiaskarov

Reputation: 5073

UIScrollView instance has property contentOffset, which can help you to detect what view is being displayed now (view1, view2, view3). I am posting example code-snippet, which helps me to determine the page number of scrollView.

  - (NSInteger)pageNumber
     {
        static NSInteger previousPage = 0;
        CGFloat pageWidth = self.scrollView.frame.size.width;
        float fractionalPage = self.scrollView.contentOffset.x / pageWidth;
        NSInteger page = lround(fractionalPage);

        NSLog(@"page number %d",page);

        if (previousPage != page) {
            previousPage = page;
            /* Page did change */
           //put here your hide/show buttons logics
        }
        return page;
    }

The best place to insert these lines is scrollView delegate's method -(void)scrollViewDidEndDecelerating:. The scroll view calls this method each time when the scrolling movement comes to a halt.

So your final version will look like:

- (void)scrollViewDidEndDecelerating:(UIScrollView *)sender
{
   [self pageNumber];
}

Upvotes: 1

Related Questions