如果现有屏幕交互在UIView上经过并停止,则运行操作

时间:2016-11-01 08:07:55

标签: ios objective-c iphone uiview

如果屏幕交互(长按)移动到uiview然后在那里停留选定的一段时间,如何向uiview添加动作。

编辑:我有一个下拉菜单类型的系统,长按按钮显示菜单。然后,用户将向下滑动到选项,然后释放该点击。我想告诉发生了哪个菜单项并采取相应的行动。

1 个答案:

答案 0 :(得分:0)

将以下手势添加到您的UIView中以获得长按功能。

    var longTap = UILongPressGestureRecognizer(target: self, action: #selector(self.longTouch))
    longTap.numberOfTapsRequired = 0 // Set your own number here
    longTap.minimumPressDuration = 1.0 //Set your duration here
    longTap.delegate = self// Add the <UIGestureRecognizerDelegate> protocol 
    self.view.addGestureRecognizer(longTap)

添加代理

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

下面是选择器将被称为

func longTouch(_ recognizer: UILongPressGestureRecognizer) {
    if recognizer.state == .began {
        print("longTouch UIGestureRecognizerStateBegan")
    }
    if recognizer.state == .ended {
        print("longTouch UIGestureRecognizerStateEnded")
    }
}

目标C版

    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTouch:)];
    [longTap setNumberOfTapsRequired:0]; // Set your own number here
    [longTap setMinimumPressDuration:1.0]; // Set your duration here
    [longTap setDelegate:self]; // Add the <UIGestureRecognizerDelegate> protocol
    [self.view addGestureRecognizer:longTap]; 

Delgate: -

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

选择器: -

- (void) longTouch: (UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"longTouch UIGestureRecognizerStateBegan");
    }
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"longTouch UIGestureRecognizerStateEnded");
    }
}