Reputation: 1015
I'd like to implement a press and hold button. So when you push the button, function A executes, and when you release, function B executes. I found this, but it wasn't what I was quite looking for.
I don't want any repeating action.
Upvotes: 4
Views: 21708
Reputation: 4042
UILongPressGestureRecognizer Swift 3 & above:
// Add Gesture Recognizer to view
let longPressGestureRecognizer = UILongPressGestureRecognizer(
target: self,
action: #selector(handleLongPress(_:)))
view.addGestureRecognizer(longPressGestureRecognizer!)
Upvotes: 1
Reputation: 1897
I have faced this problem myself, and mostly we use these events:-
// This event works fine and fires
[button addTarget:self action:@selector(holdDown)
forControlEvents:UIControlEventTouchDown];
// This does not fire at all
[button addTarget:self action:@selector(holdRelease)
forControlEvents:UIControlEventTouchUpInside];
Solution:
Use Long Press Gesture Recognizer:
UILongPressGestureRecognizer *btn_LongPress_gesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleBtnLongPressGesture:)];
[button addGestureRecognizer:btn_LongPress_gesture];
Implementation of gesture:-
- (void)handleBtnLongPressGesture:(UILongPressGestureRecognizer *)recognizer {
//as you hold the button this would fire
if (recognizer.state == UIGestureRecognizerStateBegan) {
[self buttonDown];
}
// as you release the button this would fire
if (recognizer.state == UIGestureRecognizerStateEnded) {
[self buttonUp];
}
}
Upvotes: 20
Reputation: 29524
Just add different selectors to the UIButton
based on different events. To set the selector for when you initially press down, do the following
[button addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];
and the selector for when your button is released:
[button addTarget:self action:@selector(buttonUp:) forControlEvents:UIControlEventTouchUpInside];
Upvotes: 22
Reputation: 21805
you can implement
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
method
and then check if your button lies in the touch location using CGRectContainsPoint()
then if the user moves the finger
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
will be called..here you should again check if user is still on your button..otherwise stop your function
and
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
is called when user removes finger from the screen
Upvotes: 3
Reputation: 14304
I think the best solution for you would be to implement with UIGestureRecognizer, where one would be the UITapGestureRecognizer and the other a UILongPressGestureRecognizer
Upvotes: 1