0

У меня возникли трудности с получением Sweep Gesture Recognizer для работы с моим приложением. Вот Иерархия всего этого.UISwipeGestureRecognizer Not Performing Method

Внешний вид приложения - это UINavigationController, который имеет класс ViewController, как видно для первого вида. У меня есть UIButton, который будет запускать фильм, который петли, пока я не коснусь его дважды, и у него будет контроллер навигации, который запустит новый ViewController, который я сделал с помощью PUPPETS1 на экране. Этот VC имеет свой собственный xib. Xib имеет UIImageView. То, что я хочу, - начать играть в кино, как только я проведу на экране, но этого никогда не произойдет, и консоль никогда не показывает мой NSLog из второго метода VC.

- (void)loopVideo { 

    NSURL *videoURL = [[NSBundle mainBundle] URLForResource:@"warpspeed" withExtension:@"mov"]; 
    UIView *patternView = [[UIView alloc] initWithFrame:self.view.bounds]; 
    patternView.backgroundColor = [UIColor blackColor]; 
    [self.moviePlayer2.backgroundView addSubview:patternView]; 
    self.moviePlayer2 = [[MPMoviePlayerController alloc] initWithContentURL:videoURL]; 
    [self.moviePlayer2 setControlStyle:MPMovieControlStyleDefault]; 

    self.moviePlayer2.controlStyle = MPMovieControlStyleNone; 
    self.moviePlayer2.scalingMode = MPMovieScalingModeAspectFill; 
    self.moviePlayer2.movieSourceType = MPMovieSourceTypeFile; 
    [self.moviePlayer2 setAllowsAirPlay:YES]; 
    self.moviePlayer2.view.frame = self.view.frame; 


    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(puppetOne)]; 
    tapGesture.numberOfTapsRequired = 2; 
    tapGesture.numberOfTouchesRequired = 1; 

    UIView *aView = [[UIView alloc] initWithFrame:self.moviePlayer2.backgroundView.bounds]; 
    [aView addGestureRecognizer:tapGesture]; 

    [self.view.window addSubview:aView]; 
    [self.view addSubview:self.moviePlayer2.view]; 
    self.moviePlayer2.repeatMode = MPMovieRepeatModeOne; 
    [self.moviePlayer2 play]; 

} 
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ 

    return YES; 

} 

Во 2 ВК, то PUPPETS1 один:

- (void)viewDidLoad { 
    [super viewWillAppear:YES]; 
    UISwipeGestureRecognizer * swipeRec = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(playPuppets)]; 

    swipeRec.direction = UISwipeGestureRecognizerDirectionUp; 


    UIView *aView2 = [[UIView alloc] initWithFrame:self.view.bounds]; 
    [aView2 addGestureRecognizer:swipeRec]; 
    [self.view addSubview:aView2]; 
    // Do any additional setup after loading the view from its nib. 
} 




-(void)playPuppets { 
    NSLog(@"PLAYING"); 
    NSURL *videoURL = [[NSBundle mainBundle] URLForResource:@"SundayPuppets" withExtension:@"m4v"]; 

    //filePath may be from the Bundle or from the Saved file Directory, it is just the path for the video 
    AVPlayer *player = [AVPlayer playerWithURL:videoURL]; 
    AVPlayerViewController *playerViewController = [AVPlayerViewController new]; 
    playerViewController.player = player; 
    //[playerViewController.player play];//Used to Play On start 
    [self presentViewController:playerViewController animated:YES completion:nil]; 
} 
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ 

    return YES; 

} 
+0

Почему у вас есть супер viewWillAppear: да в viewDIdLoad? Вы уверены, что метод viewDidLoad вызван для вашего второго VC? [super viewWillAppear: YES]; shud be [super viewDidLoad]; –

+0

@TejaNandamuri Это была опечатка раньше, когда я пробовал viewWillAppear. Я просто добавил NSLog в viewDidLoad, и он отображается в консоли. – user717452

+0

попытайтесь добавить распознаватель жестов в self.view вместо aView2. Я думаю, что aView не правильно обрамлен в viewDidLoad –

ответ

0

Рама зрения, к которой вы креплении гр зависит это границы родительского вида, и те, которые еще не инициализирован в viewDidLoad. Перемещение установки в после того, как макет будет завершена (и настроить его для работы только один раз, при первом изменении макета), т.е.

- (void)viewDidLayoutSubviews { 
    [super viewDidLayoutSubviews]; 

    UIView *swipeView = [self.view viewWithTag:999]; 
    // only do this if we haven't done it already 
    if (!swipeView) { 
     // now that self.view.bounds is initialized... 
     swipeView = [[UIView alloc] initWithFrame:self.view.bounds]; 
     swipeView.tag = 999; 

     // the rest of your OP setup code is fine, and goes here 
     UISwipeGestureRecognizer * swipeRec = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(playPuppets)]; 
     swipeRec.direction = UISwipeGestureRecognizerDirectionUp; 
     [swipeView addGestureRecognizer:swipeRec]; 

     [self.view addSubview:swipeView]; 
     NSLog(@"%@", swipeView); 
    } 
} 

РЕДАКТИРОВАНИЕ Код выше, присоединенную жест признания зрения правильно, обеспечивая исправление в второй контроллер просмотра. Оказывается, что другой проблемой был предыдущий контроллер представления, который неправильно удалял (устаревший) MPMoviePlayer, что приводило к неработающим касаниям на нажатом vc. Весь переработанный ViewController.m можно найти в чате связан ниже, но исправление для выпуска касаний было здесь ...

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 

    [self.moviePlayer stop]; 
    [self.moviePlayer.view removeFromSuperview]; 
    self.moviePlayer = nil; 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 
+0

Хорошо, я пробовал это, с незначительным редактированием (aView2 еще не был объявлен в вашем ответе, поэтому я добавил его), и добавил NSLogs. NSLogs каждый огонь 3 раза, но он все равно не распознает салфетки. – user717452

+0

:-) Я отклонил редактирование, потому что 'aView2' не требуется. Мой код 'swipeView' служит той же цели, но лучше назван (я думал). Попробуйте мое решение точно так же, как предложено, удалив аналогичный код из viewDidLoad. – danh

+0

Так что последняя строка просто изменится с addSubview: aView2 на swipeView? – user717452