在长按钮上显示UIView

时间:2014-10-08 11:05:40

标签: ios iphone uiview swift uibutton

也许有人已经问过这个问题,但我还没找到。

我的屏幕上有一些按钮,当用户点击一个按钮(并保持约2秒钟)时,一个新的UIView应该出现在用户正在敲击的位置。就像iOS键盘上的按钮一样,如果你点击(例如)“E”按钮,它应该显示一个包含一些额外按钮的新视图。

我没有找到任何解决方法如何做到这一点,所以如果你知道如何解决这个问题,请帮助我。

编辑: 我添加了LongPressGestureRecognizer,但这个手势永远不会被解雇。

这是我的代码:

var longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "buttonLongPressed:")
    longPressGestureRecognizer.minimumPressDuration = 1.5
    longPressGestureRecognizer.allowableMovement = 1

    for buttonTitle in buttonTitles{
        var button : UIButton!
        if(buttonTitle.length == 1) {
            button = createButtonWithTitle(buttonTitle)
        } else {
            button = createButtonWithImage(buttonTitle)
        }

        button.addGestureRecognizer(longPressGestureRecognizer)
    }


func buttonLongPressed(recognizer : UILongPressGestureRecognizer) -> (Void) {
    NSLog("tapped")
    if(recognizer.state == UIGestureRecognizerState.Failed) {
        NSLog("failed")
    }
    if(recognizer.state == UIGestureRecognizerState.Ended) {
        NSLog("ended")
    }
    if(recognizer.state == UIGestureRecognizerState.Began) {
        NSLog("began")
    }
}

2 个答案:

答案 0 :(得分:1)

    //set gesture recognizer for long press
    UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressedHandler:)];
    [button addGestureRecognizer:gestureRecognizer];
    [gestureRecognizer release];

答案 1 :(得分:1)

 UILongPressGestureRecognizer *longpress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(action:)];
                longpress.minimumPressDuration = 0.3;
 [<button> addGestureRecognizer:longpress];

- (void)action:(UILongPressGestureRecognizer *)gesture {

}

使用上面的代码片段,它可以帮助您在长按后触发动作,并且可以修改长按时间。