2016-03-30 4 views
0

Вот мой GameViewController.m файл:Почему мой UIGestureRecognizer Swipe не работает? Xcode

- (void)viewDidLoad { 
     [super viewLoad]; 
     . 
     . 
     . 
     _board = [[TwinstonesBoardModel alloc] init]; 
     [_board setToInitialStateMain]; 
     TwinstonesStoneView* twinstonesBoard = [[TwinstonesStoneView alloc] 
              initWithMainFrame:CGRectMake(12, 160, 301.5, 302.5) 
              andBoard:_board]; 
     [self.view addSubview:twinstonesBoard]; 

     TwinstonesStonesView *stoneOne = [[TwinstonesStoneView alloc] init]; 
     TwinstonesStonesView *one = (TwinstonesStoneView*)stoneOne.stoneUnoView; 
     TwinstonesStonesView *stoneTwo = [[TwinstonesStoneView alloc] init]; 
     TwinstonesStonesView *two = (TwinstonesStoneView*)stoneTwo.stoneDueView; 

     UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc] 
              initWithTarget:self 
              action:@selector(swipeLeft:)]; 
     swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; 
     swipeLeft.numberOfTouchesRequired = 1; 
     [one addGestureRecognizer:swipeLeft]; 
     [two addGestureRecognizer:swipeLeft]; 

Вот соответствующий код в моем файле TwinstonesStoneView.m:

@implementation TwinstonesStoneView 
    { 
     NSMutableArray* _array; 
     NSMutableArray* _emptyArray; 
     CGRect _frame; 
     NSUInteger _column; 
     NSUInteger _row; 
     TwinstonesBoardModel* _board; 

     int _i; 
    } 

    - (id)initWithMainFrame:(CGRect)frame andBoard: 
             (TwinstonesBoardModel*)board 
    { 
     if (Self = [super initWithFrame:frame]) 
     { 
     float rowHeight = 49.0; 
     float columnWidth = 49.0; 
     float barrierHorizontalRowHeight = 12.5; 
     float barrierVerticalColumnWidth = 12.5; 

     for (int row = 0; row < 5; row++) 
     { 
      for (int col = 0; col < 5; col++) 
      { 
      TwinstonesStonesView* square = [[TwinstonesStoneView alloc] 
       initWithEmptyFrame:CGRectFrame(//spacial equations, not important) 
       column:col 
       row:row 
       board:board]; 

      BoardCellState state = [board cellStateAtColumn:col andRow:row]; 

      if (state == BoardCellStateStoneOne) { 
       // _stoneUnoView is a public property 
       // 'stoneOneCreation' creates a UIImageView of the stone 
       _stoneUnoView = [UIImageView stoneOneCreation]; 
       [self addSubview:square]; 
       [square addSubview:_stoneUnoView]; 
       [_array insertObject:_stoneUnoView atIndex:0]; 
      } else if (state == BoardCellStateStoneTwo) { 
       // same idea as above 
       _stoneDueView = [UIImageView stoneTwoCreation]; 
       [self addSubview:square]; 
       [square addSubview:_stoneDueView]; 
       [_array insertObject:_stoneDueView atIndex:1]; 
      } else { 
       // based on the 'init' method I write below, I assumed this 
       // would return an empty square cell 
       [self addSubview:square]; 
       [_emptyArray insertObject:square atIndex:_i]; 
       _i++; 
      } 
      } 
     } 
     self.backgroundColor = [UIColor clearColor]; 
     } 
     return self; 
    } 

    - (UIView*)stoneUnoView { 
     return _stoneUnoView; 
    } 

    - (UIView*)stoneDueView { 
     return _stoneDueView; 
    } 

    - (id)initWithEmptyFrame:(CGRect)frame 
         column:(NSUInteger)column 
         row:(NSUInteger)row 
         board:(TwinstonesBoardModel*)board 
    { 
     self = [super initWithFrame:frame]; 
     return self; 
    } 

    - (void)swipeLeft:(UIGestureRecognizer*)recognizer 
    { 
     NSLog(@"Swipe Left"); 
     UIView* view = recognizer.view; 
     [self move:CGPointMake(-1, 0) withView:view]; 
    } 

    - (void)move:(CGPoint)direction withView:view { 
     // whatever code I decide to put for stone movement 
    } 

    @end 

Извиняюсь за (возможно) ненужную длиной, я просто пытаюсь чтобы понять это на пару дней и не повезло. Вот пункты, которые я пытаюсь сделать: 1. setInititalStateMain устанавливает места размещения двух камней в сетке 5x5. 2. В GameViewController.m я пытаюсь захватить «stoneUnoView» и «stoneDueView», свойства (устанавливаются в файле TwinstonesStoneView.m), дайте им жесты с помощью пальцев и взаимодействуйте с ними, используя методы, представленные в TwinstonesStoneView.m. 3. Я генерирую слишком много просмотров? Уловка в том, что все работает с точки зрения того, что я могу видеть на своем IPhone при запуске программы. Камни появляются на моем экране, но когда я пытаюсь взаимодействовать с ними, на консоли не появляется даже сообщение «NSLog». 4. Метод «stoneOneCreation» (и ... два) - это UIImageView, но, как вы можете видеть, я сохраняю их в указателе UIView.
5. Я также использовал '[one setUserInteractionEnabled: YES]' (и ... два), но это тоже не помогло. 6. Если я добавлю распознаватель жестов в self.view, все будет работать (появятся дисплеи камней, игровой доски и других графических объектов, а когда я взаимодействую с ЛЮБОЙ частью экрана, я выводю направления на консоль. .... просто не каменное взаимодействие).

Благодарим вас за то, что вы с этим справитесь, это действительно поможет, если кто-то знает, что случилось. PS: все импортированные файлы # являются правильными, так что это не проблема.

Я использую XCode 7, язык Objective-C, а также разработки для IOS

  • Энтони

ответ

0

Одна вещь, которая бросается в глаза, я не думаю, что вы можете добавить один и тот же жест распознаватель для нескольких видов. Я подозреваю, что в лучшем случае только последнее представление фактически получает его.

+0

Я закомментирована один из взглядов, чтобы попробовать его, и он до сих пор не работает. Я всегда думал, что вы можете дать один и тот же жест нескольким взглядам, поскольку сами представления представляют собой отдельные сущности. Спасибо –

+0

Я все еще уверен, что вы не можете повторно использовать жесты, но вы, похоже, удалили это как возможную проблему. У вас есть взаимодействие с пользователем в этих представлениях? Если он выключен, я верю, что жесты не будут срабатывать. – ghostatron

+0

Да, у меня есть эта строка [one setUserInteractionEnabled: YES]; включить и выключить. «один» - это TwinstonesStoneView (подкласс UIView), поэтому я не знаю, почему эта строка имеет значение. –

0

попробовать это, но я не уверен, попробуйте это, просто создать 2 салфетки жесты в GameViewController.m

- (void)viewDidLoad { 
    [super viewLoad]; 
    //.... other code 
    //comment below line 
    // UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc] 
            //initWithTarget:self //setting self is the problem is the problem 
            //action:@selector(swipeLeft:)]; 
    UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc] 
           initWithTarget:stoneOne //set target will be one 
            action:@selector(swipeLeft:)]; 
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; 
    swipeLeft.numberOfTouchesRequired = 1; 

    [one addGestureRecognizer:swipeLeft]; 

    UISwipeGestureRecognizer* swipeLeft_2 = [[UISwipeGestureRecognizer alloc] 
          initWithTarget:stoneTwo //this will be two 
          action:@selector(swipeLeft:)]; 
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft; 
    swipeLeft.numberOfTouchesRequired = 1; 

    [two addGestureRecognizer:swipeLeft_2]; //set the gesture 
} 

у настраиваете жест, чтобы self что означает, что действия направляются GameViewController.m, но мы хотим, чтобы действия были в TwinstonesStoneView.m, так что измените цель на TwinstonesStoneView. А также, если это вид изображения у добавляют жесты, а затем включить взаимодействие с пользователем для каждых просмотров изображения setUserInteractionEnabled:

просто попробовать

Смежные вопросы