Harsh.C
Harsh.C

Reputation: 83

How to segue back from one view controller to another within a custom UIView?

I want to segue back from ViewControllerTwo to ViewControllerOne. I created a button that is responsible for doing that, but my problem is that the button is part of custom UIView class that is added to ViewControllerTwo, the button is not a part of the main view of ViewControllerTwo.

So in the custom UIView class I have the method that reacts if the button is clicked...

-(void)buttonClicked{
    [SecondViewController performSegueWithIdentifier: "ShowFirstViewController" sender:nil];
 }

When I do this I get an error: "performSegueWithIdentifier not a method of class" which makes sense.

So how can I segue between two viewcontrollers where the button responsible for the segue is not actually part of either view controller and is in a different class.

Upvotes: 2

Views: 145

Answers (2)

Shreesha Kedlaya
Shreesha Kedlaya

Reputation: 350

I think you can have a delegate call back to your SecondViewController and implement the performSegueWithIdentifier in the delegate callback method in SecondViewController.

It goes like this:

Above your custom UIView class interface create a protocol like this

@protocol CustomViewDelegate <NSObject>
- (void)buttonDidTap;
@end

Then create a property in your interface

@property (nonatomic, weak) id <CustomViewDelegate> delegate;

In your custom UIView *.m add this

-(void)buttonClicked{
    [self.delegate buttonDidTap];
 }

Conform the protocol to your SecondViewController like this

@interface SecondViewController: UIViewController <CustomViewDelegate>

set the delegate in your viewDidLoadMethod like this

-(void)viewDidLoad{
[super viewDidLoad];
self.yourCustomView.delegate = self;
}

implement this method inside the view controller .m file

- (void)buttonDidTap{
[self.performSegueWithIdentifier: "ShowFirstViewController" sender:self];
}

I'm more of a swift guy i think this should work fine.

Upvotes: 1

serge-k
serge-k

Reputation: 3512

iOS 9.3, Xcode 7.3, ARC enabled

This is what I'd do to troubleshoot:

Step 1: Make sure that you have a proper storyboard identifier for the view controllers you wish to segue between. The views simply attach to the view controllers, custom or not.

To do this, go to "*.storyboard" show the Utilities (right pane) and navigate to the Identity Inspector. Make sure you have "ShowFirstViewController" entered in the Storyboard ID field.

enter image description here

Upvotes: 0

Related Questions