0
votes

My gesture recognizers stopped working when I switched to programmatically creating a UIView rather than using a xib. Question: how can I programmatically implement gesture recognition using just a custom view controller and no custom UIView or is this not possible?

I know some think this is bad practice, but that's not my question. I'd rather not have to move the gesture-related functions to a UIView subclass because then I'll just be setting up a delegate protocol of some kind for the view to tell the view controller about the gesture, which seems quite roundabout when I'm happy having it all in the view controller. Interface builder and the xib must have done something I can do programmatically - what was it?

Here's my code in case it's relevant. The gesture recognizers all worked fine with the xib.

@interface CustomViewController () <UITextFieldDelegate, UINavigationControllerDelegate, UIGestureRecognizerDelegate, UITableViewDataSource, UITableViewDelegate,  UIViewControllerRestoration, UIScrollViewDelegate>

-(id)init
{
    self = [super init];

    if(self){
....
        CGFloat height = [[UIScreen mainScreen] bounds].size.height;
        CGFloat width = [[UIScreen mainScreen] bounds].size.width;
        UIView *sv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
        sv.backgroundColor = [UIColor redColor];
        self.view = sv;
...
    }   
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwipe];


    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:leftSwipe];


    UISwipeGestureRecognizer *upSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeUp:)];
    upSwipe.direction = UISwipeGestureRecognizerDirectionUp;
    upSwipe.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:upSwipe];    
}

Thank you for any suggestions.

1

1 Answers

1
votes

I don't think that viewDidLoad will even be called given your code. All the code you have for creating the controller's view, that's now in init, should be moved to loadView. If you put the code there, then viewDidLoad will be called.