简体   繁体   中英

Adding a tapGestureRecognizer to a Custom UIView with xib

Background: I have an array of questions that are the basis for setting up a bunch of uiviews and laying them out on the screen. Each uiview has a title and an imageview. I would like to add a tap gesture recognizer to the imageview and have the uiview be the gesture delegate.

The problem: Cannot get the gesture to be picked up by the uiview.

What I have tried so far: If I init the view in code with init with frame, instead of loading the xib through the main bundle with the viewcontroller as owner, works without modifying the gesture code. So I think the problem must lie in how and when to add the gesture recognizer. Currently im using a setup method which loads in the question name and then adds it there. Adding it in awake from nib doesnt work.

This is the code in the loop that loads each uiview

NSArray* bundle = [[NSBundle mainBundle] loadNibNamed:@"QnA" owner:self options:nil];

QuestionAnswer *qa;
for (id object in bundle) {
    if ([object isKindOfClass:[QuestionAnswer class]])
        qa = (QuestionAnswer *)object;
    }

CGRect f = qa.frame;
f.origin.x = x;
f.origin.y = y;
qa.frame = f;
[self.view addSubview: qa];
[qa setup:[questions objectAtIndex:i ]];

And this is the "setup" method in the QuestionAnswer class

-(void)setup:(NSString *)label
{
    self.afl.text = label;
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTapped:)];
    tgr.delegate = self;
    [self addGestureRecognizer:tgr];

}

QuestionAnswer implements UIGestureRecognizerDelegate. I have a breakpoint at the firstline of imageTapped and it never gets there. I have also tried applying the gesture recognizer directly to the imageview to no avail.

The viewcontroller is in a splitview controller, dont think that has relevance as the recognizer worked when I init the view in code. :/

在viewDidLoad方法中添加手势识别器。

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