IOS slide menu implementation

Source: Internet
Author: User

During the project today, the product manager said that many apps have achieved similar effects, such as Netease news and sogou input boards, to achieve a slide menu similar to facebook. So I searched for the Implementation Principles on the Internet. Although I found a lot, I found that their implementation was too complicated and the Code seemed to be difficult. I am a very simple and clear-minded person, I strongly advocate that everything is simple, and it is not complicated to be simple, so I tried to implement it myself.


First, let's briefly talk about the implementation principle: Two uiviews are needed, one is the CenterView in the middle, and the other is the LeftView displayed on the left when sliding. Add LeftView to ViewController first, and then add CenterView. In this way, CenterView will cover the LeftView. At the beginning, it will naturally be CenterView. Because slide is performed on CenterView, you need to add Gesture Recognition to CenterView. When sliding, the coordinates of the center point of CenterView are changed, so that the covered LeftView is displayed. This is the basic principle of implementation. I will analyze it in detail below.


Let's first look at LeftView. to distinguish it from CenterView, I set its background to red, and then put a button in the middle:


LeftView. h

/// LeftView. h // SlideView /// Created by hejinlai on 13-8-13. // Copyright (c) 2013 yunzhisheng. all rights reserved. // # import <UIKit/UIKit. h> @ interface LeftView: UIView @ end


LeftView. m

/// LeftView. m // SlideView /// Created by hejinlai on 13-8-13. // Copyright (c) 2013 yunzhisheng. all rights reserved. // # import "LeftView. h "@ implementation LeftView-(id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {// Initialization code self. backgroundColor = [UIColor redColor]; UIButton * btn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; btn. frame = CGRectMa Ke (0, 0,100, 50); [btn setTitle: @ "LeftView" forState: UIControlStateNormal]; btn. center = CGPointMake (140,264); [btn addTarget: self action: @ selector (onClick :) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: btn];} return self;}-(void) onClick :( UIButton *) button {NSLog (@ "LeftView button pressed! ");} @ End


Let's take a look at CenterView. First, we declare the coordinates of the center of the screen and a gesture recognition:


#import <UIKit/UIKit.h>@interface CenterView : UIView{    UIPanGestureRecognizer *panGestureRecognizer;    float centerX;    float centerY;}@end


When CenterView is initialized, calculate the coordinates of the center of the screen, set the background to green, and add buttons and Gesture Recognition in the upper left corner.


-(Id) initWithFrame :( CGRect) frame {self = [super initWithFrame: frame]; if (self) {CGRect screen = [[UIScreen mainScreen] bounds]; centerX = screen. size. width/2; centerY = screen. size. height/2; self. backgroundColor = [UIColor greenColor]; // UIButton * leftUpBtn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; leftUpBtn in the upper left corner. frame = CGRectMake (10, 10, 40, 40); [leftUpBtn addTarget: self action: @ selector (buttonPressed :) forControlEvents: UIControlEventTouchUpInside]; [self addSubview: leftUpBtn]; panGestureRecognizer = [[initalloc] initWithTarget: self action: @ selector (handlePan :)]; [self addGestureRecognizer: panGestureRecognizer];} return self ;}



The final position of CenterView is actually two: the first position is filled with the entire screen, and its center is the center of the screen, covering the entire LeftView; the second position is the center on the right, only a small part is displayed on the left side of the screen, so that the LeftView at the bottom can be displayed.


I set the horizontal coordinate of the rightmost center of CenterView to 420, which is equivalent to 60 on the left of CenterView on the screen. Another problem is: when the slide stops, does CenterView return to the first or second position? Here I set a boundary value of 280. If the abscissa of the center is smaller than 280, it returns to the first position. If it is greater than 280, it returns to the second position. The following is the definition of the two constants:


#define MAX_CENTER_X 420#define BOUND_X 280


Of course, these two values can be adjusted as needed.


When you click the button in the upper-left corner of CenterView, you need to switch between the two positions, that is, if the first position is to return to the second position, the second position is to return to the first position:


- (void)buttonPressed:(UIButton *)button{    [UIView animateWithDuration:0.2 animations:^(void){                                                                                                                         if (self.center.x == centerX) {            self.center = CGPointMake(MAX_CENTER_X, centerY);        }else if (self.center.x == MAX_CENTER_X){            self.center = CGPointMake(centerX, centerY);        }                                                                                                                     }];                                                                                                             }


Animation effects are added to make it look smoother.


Next, let's look at the processing logic for sliding. First, calculate the center point abscissa After sliding:


CGPoint translation = [recognizer translationInView:self];    float x = self.center.x + translation.x;


Since CenterView cannot be moved to the left side, that is, the minimum value of the central point of CenterView is centerX. When the central point coordinate is smaller than this value, you need to reset it:


if (x < centerX) {        x = centerX;    }    self.center = CGPointMake(x, centerY);


When the slide ends, you need to determine the area to which the left of the center falls. If it is smaller than the boundary value, it returns to the first position. If it is greater than the boundary value, it returns to the second position. In order to look smoother, added animation effects:


if (recognizer.state == UIGestureRecognizerStateEnded) {                                                   [UIView animateWithDuration:0.2 animations:^(void){                                                           if (x > BOUND_X) {                self.center = CGPointMake(MAX_CENTER_X, centerY);            }else{                self.center = CGPointMake(centerX, centerY);            }                                                       }];                                                                                          }                                           [recognizer setTranslation:CGPointZero inView:self];


Finally, add the two uiviews to ViewController. Note that LeftView is added first, and then CenterView is added:


- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.                                      CGRect screen = [[UIScreen mainScreen] bounds];    CGFloat width = screen.size.width;    CGFloat height = screen.size.height;                                      leftView = [[LeftView alloc] init];    leftView.frame = CGRectMake(0, 0, width, height);    [self.view addSubview:leftView];                                      centerView = [[CenterView alloc] init];    centerView.frame = CGRectMake(0, 0, width, height);    [self.view addSubview:centerView];}


Running result:


650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/06325Mc2-0.png "title =" IMG_0552.PNG "/>


For the convenience of testing, I uploaded the source code in the attachment. You are welcome to download it!

This article is from the "mobile development" blog, please be sure to keep this source http://ikinglai.blog.51cto.com/6220785/1272238

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.