2013-11-08 2 views
1

Я создал SlidingViewController с главными, правыми и левыми контроллерами. Теперь я хочу добавить новую функцию/метод, которая вызывается всякий раз, когда нажимается одна из ячеек таблицы видения RightViewController, чтобы переключить главный контроллер представления на то, что когда-либо контроллер просмотра связан с этой ячейкой просмотра таблицы в indexpath.row. Новый контроллер просмотра должен все же иметь доступ к этому доступному контроллеру справа и слева. У кого-нибудь есть опыт создания собственного SlidingViewController или MenuViewController, который может помочь в том, как я должен подходить к этому? Любая помощь будет с благодарностью оценена. Заранее спасибо.Добавление нового контроллера вида в пользовательский скользящий ViewController с левым, правым и основным контроллером представления

SlidingViewController.h

@interface SlidingViewController : UIViewController <UIGestureRecognizerDelegate> 

@property (retain) UIViewController *mainViewController; 
@property (retain) UIViewController *leftViewController; 
@property (retain) UIViewController *rightViewController; 
@property (retain) NSNumber *leftSwipeEnabled; 
@property (assign) BOOL leftDrawerVisible; 
@property (retain) NSNumber *rightSwipeEnabled; 
@property (assign) BOOL rightDrawerVisible; 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil mainViewController:(UIViewController *)main leftViewController:(UIViewController *)left andRightViewController:(UIViewController *)right; 
-(void)toggleLeftDrawer; 
-(void)toggleRightDrawer; 
@end 

SlidingViewController.m

@implementation SlidingViewController 
@synthesize mainViewController, leftViewController, rightViewController; 
@synthesize leftDrawerVisible, rightDrawerVisible; 
@synthesize leftSwipeEnabled, rightSwipeEnabled; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil mainViewController:(UIViewController *)main leftViewController:(UIViewController *)left andRightViewController:(UIViewController *)right 
{ 
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
    { 
     mainViewController = main; 
     leftViewController = left; 
     rightViewController = right; 
     leftSwipeEnabled = [NSNumber numberWithBool:NO]; 
     rightSwipeEnabled = [NSNumber numberWithBool:NO]; 
    } 

    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self addChildViewController:self.mainViewController]; 
    [self.view addSubview:[self.mainViewController view]]; 
    self.mainViewController.view.frame = self.view.frame; 
    [self.mainViewController didMoveToParentViewController:self]; 

    self.mainViewController.view.layer.shadowColor = [UIColor blackColor].CGColor; 
    self.mainViewController.view.layer.shadowOpacity = 0.2f; 
    self.mainViewController.view.layer.shadowRadius = 5.0f; 
    CGPathRef path = [UIBezierPath bezierPathWithRect:self.mainViewController.view.bounds].CGPath; 
    self.mainViewController.view.layer.shadowPath = path; 

    if(self.leftViewController != nil) 
    { 
     UISwipeGestureRecognizer *leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 
     leftSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight; 
     leftSwipeRecognizer.delegate = self; 
     [self.mainViewController.view addGestureRecognizer:leftSwipeRecognizer]; 
    } 
    if(self.rightViewController != nil) 
    { 
     UISwipeGestureRecognizer *rightSwipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)]; 
     rightSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft; 
     rightSwipeRecognizer.delegate = self; 
     [self.mainViewController.view addGestureRecognizer:rightSwipeRecognizer]; 
    } 



} 
-(void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    [self layoutShadowWithDuration:0]; 
} 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesBegan:touches withEvent:event]; 
    if(self.leftDrawerVisible) 
     [self toggleLeftDrawer]; 
    else if(self.rightDrawerVisible) 
     [self toggleRightDrawer]; 
} 
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer 
{ 
    return YES; 
} 
-(void)handleSwipe:(UISwipeGestureRecognizer *)recognizer 
{ 

    if(recognizer.state == UIGestureRecognizerStateEnded) 
    { 
     if(recognizer.direction == UISwipeGestureRecognizerDirectionRight && [self.leftSwipeEnabled boolValue]) 
      [self toggleLeftDrawer]; 
     else if(recognizer.direction == UISwipeGestureRecognizerDirectionLeft && [self.rightSwipeEnabled boolValue]) 
      [self toggleRightDrawer]; 
    } 
} 
-(void)toggleLeftDrawer 
{ 
    if (self.rightDrawerVisible) 
    { 
     return; 
    } 
    if(self.leftDrawerVisible) 
    { 
     [UIView animateWithDuration:0.2 
           delay:0.0 
          options:UIViewAnimationOptionCurveLinear 
         animations:^{ 
          self.mainViewController.view.frame = CGRectMake(0.0, 0.0, self.mainViewController.view.frame.size.width, self.mainViewController.view.frame.size.height);} 
     completion:^(BOOL finished) 
     { 
      [self.leftViewController.view removeFromSuperview]; 
      [self.leftViewController willMoveToParentViewController:nil]; 
      [self.leftViewController removeFromParentViewController]; 
     }]; 
     self.leftDrawerVisible = NO; 
     self.mainViewController.view.userInteractionEnabled = YES; 
    } 
    else 
    { 
     [self addChildViewController:self.leftViewController]; 
     [self.view insertSubview:[self.leftViewController view] belowSubview:[self.mainViewController view]]; 
     [self.leftViewController didMoveToParentViewController:self]; 

     CGPathRef path = [UIBezierPath bezierPathWithRect:self.mainViewController.view.bounds].CGPath; 
     self.mainViewController.view.layer.shadowPath = path; 

     self.mainViewController.view.layer.shadowOffset = CGSizeMake(-3, 0); 
     NSInteger width = 260; 

     if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) 
      width = 320; 

     self.leftViewController.view.frame = CGRectMake(0, 0, width, self.view.bounds.size.height); 

     [UIView animateWithDuration:0.2 
           delay:0.0 
          options:UIViewAnimationOptionCurveLinear 
         animations:^{ self.mainViewController.view.frame = CGRectMake(width, 0, self.mainViewController.view.frame.size.width, self.mainViewController.view.frame.size.height); } 
         completion:^(BOOL finished) { self.leftViewController.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin; }]; 
     self.leftDrawerVisible = YES; 
     self.mainViewController.view.userInteractionEnabled = NO; 
    } 
} 
-(void)toggleRightDrawer 
{ 
    if(self.leftDrawerVisible) 
     return; 

    if(self.rightDrawerVisible) 
    { 
     [UIView animateWithDuration:0.2 
           delay:0.0 
          options:UIViewAnimationOptionCurveLinear 
         animations:^{ 
          self.mainViewController.view.frame = CGRectMake(0.0, 0.0, self.mainViewController.view.frame.size.width, self.mainViewController.view.frame.size.height); 
         } 
         completion:^(BOOL finished){ 
          [self.rightViewController.view removeFromSuperview]; 
          [self.rightViewController willMoveToParentViewController:nil]; 
          [self.rightViewController removeFromParentViewController]; 
         }]; 
     self.rightDrawerVisible = NO; 
     self.mainViewController.view.userInteractionEnabled = YES; 
    } 
    else 
    { 
     [self addChildViewController:self.rightViewController]; 
     [self.view insertSubview:[self.rightViewController view] belowSubview:[self.mainViewController view]]; 
     [self.rightViewController didMoveToParentViewController:self]; 

     CGPathRef path = [UIBezierPath bezierPathWithRect:self.mainViewController.view.bounds].CGPath; 
     self.mainViewController.view.layer.shadowPath = path; 

     self.mainViewController.view.layer.shadowOffset = CGSizeMake(3, 0); 

     NSInteger width = 260; 
     if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) 
      width = 320; 
     self.rightViewController.view.frame = CGRectMake(self.view.bounds.size.width- width, 0, width, self.view.bounds.size.height); 
     [UIView animateWithDuration:0.2 delay:0.0 
          options:UIViewAnimationOptionCurveLinear 
         animations:^{ 
          self.mainViewController.view.frame = CGRectMake(-width, 0, self.mainViewController.view.frame.size.width, self.mainViewController.view.frame.size.height); 
         } 
         completion:^(BOOL finished){ 
          self.rightViewController.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin; 
         }]; 
     self.rightDrawerVisible = YES; 
     self.mainViewController.view.userInteractionEnabled = NO; 
    } 
} 

-(void) layoutShadowWithDuration:(NSTimeInterval)duration 
{ 
    CGPathRef oldShadowPath = self.mainViewController.view.layer.shadowPath; 

    if (oldShadowPath) 
    { 
     CFRetain(oldShadowPath); 
    } 

    // Update shadow path for the view 
    CGPathRef path = [UIBezierPath bezierPathWithRect:self.mainViewController.view.bounds].CGPath; 
    self.mainViewController.view.layer.shadowPath = path; 

    // You would think setting duration to 0 would cause the animation added below to not animate. You would be wrong. 
    if (duration != 0) 
    { 
     if (oldShadowPath) 
     { 
      [self.mainViewController.view.layer addAnimation:((^ { 
       CABasicAnimation *transition = [CABasicAnimation animationWithKeyPath:@"shadowPath"]; 
       transition.fromValue = (__bridge id)oldShadowPath; 
       transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; 
       transition.duration = duration; 
       return transition; 
      })()) forKey:@"transition"]; 
      CFRelease(oldShadowPath); 
     } 
     else 
      if (oldShadowPath) 
       CFRelease(oldShadowPath); 
    } 
    else 
     if (oldShadowPath) 
      CFRelease(oldShadowPath); 
} 

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { 
    [self layoutShadowWithDuration:duration]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 
@end 
+0

вы хотите изменить содержание MainViewController при RightView нажатии? – Bhavesh

+0

@iBhavesh Я хочу изменить текущий MainView всякий раз, когда щелкнет ячейка просмотра таблицы справа. По сути, мы заменим контроллеры представлений. – Chris

ответ

4

Вы можете просто сделать это "Делегирование Design Pattern"

В RightViewController.h добавить следующие строки.

@protocol RightViewControllerDelegate <NSObject> 

@required 
    - (void)somethingClicked : (id)theObject; 

@end 

@interface RightViewController : UIViewController 

@property (nonatomic, assign) id<RightViewControllerDelegate> delegate; 

@end 

В RightViewController.m добавить следующие строки.

- (void)somethingClicked : (id)theObject 
{ 
    [_delegate somethingClicked:theObject]; 
} 

Обновление MainViewController.h со следующим кодом.

@interface MainViewController : UIViewController <RightViewControllerDelegate> 

И наконец добавить следующий код в MainViewController.m

- (void)somethingClicked : (id)theObject 
{ 
    // Perform Your Task 
} 
Смежные вопросы