Reputation: 398
I have a viewcontroller (vc1) in which I added another viewcontroller (vc2) as a subview. An UITapGestureRecognizer is triggered when you tap on a view (tappingView) contained in the subview (vc2). I would like to handle this tap inside the subview controller (vc2), and not from the first viewcontroller (vc1)... but it keeps crashing when I click on my view.
Here is the hierarchy sum up :
-vc1
--vc2
---tappingView
And here is a sample of code :
ViewController1 (viewDidLoad):
- (void)viewDidLoad
{
ViewController2 *vc2 = [[ViewController2 alloc] init];
[[self view] addSubview:[vc2 view]];
}
ViewController2 (viewDidLoad):
- (void)viewDidLoad
{
UIView *tappingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60.0, 80.0)];
[[self view] addSubview:tappingView];
UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
[tappingView addGestureRecognizer:tapGestureRecognize];
}
ViewController2 (singleTapeGestureRecognizer:) :
- (void)singleTapGestureRecognizer:(id)sender {
NSLog(@"Tap gesture");
}
When I click in my view (tappingView), I keep getting a crash (BAD_ACCESS).
Anyone have an idea why ?
Upvotes: 2
Views: 359
Reputation: 5186
use below code
- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)sender
instead of
- (void)singleTapGestureRecognizer:(id)sender.
As it must have UIGestureREcognizer instead of id.`
Upvotes: -1
Reputation: 11134
In this block
- (void)viewDidLoad
{
ViewController2 *vc2 = [[ViewController2 alloc] init];
[[self view] addSubview:[vc2 view]];
}
your ViewController2
is not retained (addSubview
only retains the view, not the view controller).
To fix it, declare vc2
as a strong
property, instead of a variable.
self.vc2 = [[ViewController2 alloc] init];
Or better, as someone suggested, add vc2
as a child view controller.
Upvotes: 1
Reputation: 3368
Targets of UITapGestureRecognizer
take the UIGestureRecognizer
argument, not id
. I.e.:
- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)sender {
NSLog(@"Tap gesture");
}
Further, you're setting frames in viewDidLoad
, which you should do in viewWillAppear:
instead.
Upvotes: 0
Reputation: 104082
You shouldn't just add another view controller's view to your view -- you should make that controller a childViewController of vc1. Change the viewDidLoad in vc1 to this:
- (void)viewDidLoad {
ViewController2 *vc2 = [[ViewController2 alloc] init];
[self addChildViewController:vc2];
[vc2 didMoveToParentViewController:self];
[[self view] addSubview:[vc2 view]];
}
It's not clear why you're doing it this way in the first place. Why not present vc2 as a modal view controller instead?
Upvotes: 2