Question

I write a simple application with Xcode 5 on iPhone iOS7 device. I have a label that increments by +/- Buttons, but i want to give option for user to insert his number to this label. How can i do it with long press recogniser? Thanks.

Was it helpful?

Solution

Use a UILongPressGestureRecognizer and a UITextView.

Add a UILongPressGstureRecognizer property to your view controller:

@property UILongPressGestureRecognizer *gestureRecognizer;

You need to declare that your view controller conforms to the UITextViewDelegate and UIGestureRecognizerDelegate protocols:

@interface ViewController : UIViewController<UITextViewDelegate, UIGestureRecognizerDelegate>

In viewDidLoad:

self.textView.editable = NO;
self.textView.delegate = self;
self.gestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(textViewLongPressed:)];
self.gestureRecognizer.delegate = self;
[self.textView addGestureRecognizer:self.gr];

This is the method that will be called when you long press the text view:

-(void) textViewLongPressed:(UILongPressGestureRecognizer *)sender
{
    self.textView.editable = YES;
    [self.textView becomeFirstResponder];
}

Implement this method from the UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if (self.gestureRecognizer == gestureRecognizer){
        return YES;
    }
    return NO;
}

When you finish editing the text view

-(void) textViewDidEndEditing:(UITextView *)textView
{
    self.textView.editable = NO;
}

To dismiss the keyboard when you press return:

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
        [textView resignFirstResponder]; // or [textView endEditing:YES]

    return YES;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top