简体   繁体   中英

Gesture recogniser in different class?

I was wondering if this was possible. To have a class which adds new imageViews to the main view and assigns a gesture recogniser to it.

So in my view builder class, I have the following:

UIImageView *headerPlusIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"plusIcon.png"]];
headerPlusIcon.frame = CGRectMake(header.frame.size.width - 2.5*(logoSize - 8), yPosition*1.6, logoSize*0.9, logoSize*0.9);
headerPlusIcon.userInteractionEnabled = YES;

UIGestureRecognizer *headerTapGesture = [[UIGestureRecognizer alloc] initWithTarget:mainView action:@selector(testTapGesture:)];
[headerPlusIcon addGestureRecognizer:headerTapGesture];

The tap gesture method goes like this:

-(void)testTapGesture:(UITapGestureRecognizer *)gesture
{
    dispatch_async(dispatch_get_main_queue(), ^{
        mainView.backgroundColor = [UIColor redColor];
    });
}

mainView is passed into this class via the constructor and is simply the main view.

This is called like this:

mainViewbuilder = [[MainViewBuilder alloc] initWithBaseView:self.view];
[mainViewbuilder buildHeader];

Unfortunately the tap gesture method never gets called... how would this be done properly? Thanks!

Try UITapGestureRecognizer

Apple Docs on UITapGestureRecognizer

The code you posted never adds your headerPlusIcon to the view hierarchy. You say in your answer to Adam that you got it working, but I don't see how if you don't add the headerPlusIcon to your view controller's content view hierarchy somewhere.

Note that mucking around in a view controller's view hierarchy from outside is not good object-oriented design.

It would be better to have the view controller ask another object for a view (probably through a protocol) and then add that view itself.

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