结束触摸时的按钮事件

时间:2017-01-04 15:13:07

标签: ios objective-c

我想制作录音笔应用程序。该 录音应该在长时间触摸开始时开始 当用户停止按钮上的手势时,录制必须结束。

UIGestureRecognizer *longGesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(startrecording)];

当用户离开按钮时,我该如何处理?

2 个答案:

答案 0 :(得分:1)

在viewDidLoad方法

UILongPressGestureRecognizer *longPressOnButton = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOnButton:)];
longPressOnButton.delegate = self;
btn.userInteractionEnabled = YES;
[btn addGestureRecognizer:longPressOnButton];



- (void)longPressOnButton:(UILongPressGestureRecognizer*)gesture
{
    // When you start touch the button
    if (gesture.state == UIGestureRecognizerStateBegan)
    {
       //start recording
    }
    // When you stop touch the button
    if (gesture.state == UIGestureRecognizerStateEnded)
    {
        //end recording
    }
}

您也可以尝试或使用touchEvent概念

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)e {
    // show touch-began state
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)e {

}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)e {
    UITouch *touch = [touches anyObject];
    .....
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)e {

}

答案 1 :(得分:0)

正如user3182143所说,使用UILongPressGestureRecorgnizer将解决您的问题,但如果您感兴趣,还有另一种使用UIButton的方法。无需添加UILongPressGestureRecorgnizer

在故事板中,为IBAction拖动UIButton。在您添加其名称时,会将event更改为Touch Down

现在为同一个IBAction拖动另一个UIButton,在更改其名称时,将事件更改为Touch up Inside(如果已经不存在)。

- (IBAction)touchDownButtonAction:(UIButton *)sender {
    NSLog(@"Start");
}

- (IBAction)touchUpInsideButtonAction:(UIButton *)sender {
    NSLog(@"End");
}

根据操作处理您的录音!

以下是一个屏幕截图:

enter image description here