Search code examples
iphoneiosuiviewuiswipegesturerecognizer

Slide-able UIView menu that responds to UIGestureRecognizer


So what I am trying to do with this view is make it so that i can slide the UIView (menuView) up and down in and out of the screen. So in storyboard/IB i placed a UIView and connected it to files owner and all that jazz. then i entered the program the below code. The problem is that when the nib loads it doesnt put the UIView where it should be in the first place and then the swipe doesn't work on it. I tried this method of programming with a button and it worked fine. Thanks in advance for any help you may have on the subject.

.h file

UIView *menuView;
}
@property (strong, nonatomic) IBOutlet UIView *menuView;

.m file

@synthesize menuView;



- (void)viewDidLoad
{
[super viewDidLoad];

// Do any additional setup after loading the view.

UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc]     initWithTarget:self action:@selector(swipe:)];
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionDown];
[self.view addGestureRecognizer:swipeGesture];


menuView = [[UIView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)];
[menuView setFrame:CGRectMake(0, -80, 320, 80)];

[self.view addSubview:menuView];
}


-(void)swipe:(UISwipeGestureRecognizer*)sender {
[UIView animateWithDuration:0.5 animations:^{
    [menuView setFrame:CGRectMake(0, 0, 320, 80)];
}];
    }



 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
 }

Solution

  • You've set up your menuView as a storyBoard/IB outlet. That means the xib/nib/storyboard is doing the alloc-init and initial framing. So you should remove this line:

    menuView = [[UIView alloc] initWithFrame:CGRectMake(0, -80, 320, 80)];
    

    You can also remove the next line from viewdidLoad:

    [menuView setFrame:CGRectMake(0, -80, 320, 80)];
    

    There it's superfluous. It was already done by "initWithFrame" -- which is already done by the nib.

    On the other hand, it might be hard to position something offscreen in a nib. So you might actually reinstate the setFrame: line -- but in viewWillAppear rather than viewDidLoad. viewWillAppear is called after the nib has done its thing, so the nib is out of the way and won't interfere with your reframing.

    Make those changes and, if "all that jazz" includes connecting menuView to a reference outlet, you should be good to go.