正确使用LongPressGestureRecognizer的方法

时间:2019-02-14 15:52:21

标签: ios eventhandler uilongpressgesturerecogni

我对于在UILongPressGestureRecognizer(LPGR)的处理程序中在何处以及如何实例化变量感到困惑。

我用以下方法创建LPGR:

-(void) createLongPress {
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]
                                           initWithTarget:self action:@selector(handleLongPress:)];
[self.view addGestureRecognizer:longPress];
}

但是,由于反复调用处理程序,所以我不确定如何以及在何处实例化变量。

以下代码有效,但我担心它会反复实例化变量。我应该将它们移入         case UIGestureRecognizerStateBegan: state,我相信它只会被调用一次,还是可以将方法的顶部放在一遍又一遍被调用的方法上。

这是我的处理程序中的代码

    - (IBAction)handleLongPress:(id)sender {
        //ALL THIS CODE IS CALLED OVER AND OVER
//Does this mean these variables are getting instantiated over and over?
        UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;
        UIGestureRecognizerState state = longPress.state;
        CGPoint location = [longPress locationInView:self.view];

        switch (state) {
            case UIGestureRecognizerStateBegan: {
                //Code called just once at beginning

                  //DO SETUP            }
                break;
            } 
            case UIGestureRecognizerStateChanged: {
               //Update stuff
                                     }
                break;
            }

            case UIGestureRecognizerStateEnded: {
                    //cleanup
                }
            default: {
              //handle default case                
               }           
                break;
            } 
    }

0 个答案:

没有答案