简体   繁体   中英

How to segue to another view controller when a subview with a gesture is tapped?

I have a view controller with a subview: gestureView that is referenced by the view controller via an outlet. I have assigned a tap gesture from viewDidLoad of the parent view controller to gestureView like:

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self.gestureView action:@selector(handleTap)];
[self.gestureView addGestureRecognizer:tapGesture];

gestureView uses a custom class where handleTap: is implemented and it works fine, I can log from gestureView's handleTap:, however how can I perform a segue from the current view controller to another view controller when gestureView is tapped.

I understand that there may be easier ways to do this, but this works best for my situation.

You can use Delegate pattern or Notification pattern. Both will work in your case, As -handleTap() method is implemented in your subview you can create protocol in your subview class . And when you get handleTap method you can call delegate method which should be implemented in your parent class.

In your subview class Above class declaration define protocol

@protocol SubViewClassDelegate <NSObject>
@required;
- (void) subviewDidTapped:(id) sender;
@end

Define property of delegate.

@property (nonatomic, unsafe_unretained) id<SubViewClassDelegate> delegate;

In implementation file of subview's class call delegate method.

- (void) handleTap   {
        if ([self.delegate respondsToSelector:@selector(subviewDidTapped:)]) {
[self.delegate subviewDidTapped:yourObject]; // in yourObject you can pass data if require.
}
}

In your parent class implemented delegate of subview class

@interface ParentViewController : UIViewController <SubViewClassDelegate>

In viewDidLoad

self.gestureView.delegate = self;

And Implement the delegate method of Subview class in Parent controller.

-(void) subviewDidTapped:(id)sender {

 // Navigate using performSegueWithIdentifier:
[self performSegueWithIdentifier: @"segueIdentifier" sender: self];
 }

In the handleTap , perform a segue to the other view controller you intend to display next.

 [self performSegueWithIdentifier: @"YOU_SEGUE_IDENTIFIER" sender: self];

The segue that you will perform is the segue in the storyboard that is from current view controller to the next view controller. (You need to create this).

You can pass parameters on to the next view controller in the prepareForSegue:sender: , once you identify that it is the correct sender by checking the segue identifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM