Search code examples
iosobjective-cuigesturerecognizerswipegestures

How can I add swipe gestures to 3 different UILabels?


I'm new to XCODE - Objective-C and in my very first app I need to add to 3 different labels 2 swipe gestures (Up and down swipe).

To be more clear (for now i cannot add images) i have the 3 labels like this:

                           [label1].[label2][label3]

Min value for all labels is '0' Max value for label1 is '2', for label2 and label3 is '9' each one.

When I swipe down labels i need to decrease value and when i swipe up i need to decrease value.

How can I do this? in an example that I made before I did it but only works for 1 single UILabel.

Thanks a lot in advance. Regards.


Solution

  • You need to initialise 3 swipes, each label a swipe itself. I propose using tags to differ labels.

    Here is the code that creates labels programmatically:

    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
    label1.text = @"Label 1";
    label1.tag = 10;
    label1.userInteractionEnabled = YES;
    UISwipeGestureRecognizer *swipe1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLabel:)];
    [label1 addGestureRecognizer:swipe1];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(50, 150, 100, 100)];
    label2.text = @"Label 2";
    label2.tag = 20;
    label2.userInteractionEnabled = YES;
    UISwipeGestureRecognizer *swipe2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLabel:)];
    [label2 addGestureRecognizer:swipe2];
    
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(50, 250, 100, 100)];
    label3.text = @"Label 3";
    label3.tag = 30;
    label3.userInteractionEnabled = YES;
    UISwipeGestureRecognizer *swipe3 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLabel:)];
    [label3 addGestureRecognizer:swipe3];
    
    [self.view addSubview:label1];
    [self.view addSubview:label2];
    [self.view addSubview:label3];
    

    The swipe method:

    - (void)didSwipeLabel:(id)sender
    {
        // Parse the swipe gesture
        UISwipeGestureRecognizer *swipe = sender;
        // Get the view that called swipe
        UILabel *swipedLabel = (UILabel *)swipe.view;
        // Switch tag
        switch (swipedLabel.tag) {
            case 10:
                NSLog(@"Swiped label 1");
                break;
            case 20:
                NSLog(@"Swiped label 2");
                break;
            case 30:
                NSLog(@"Swiped label 3");
                break;
            default:
                break;
        }
    }
    

    If you prefer to use Interface Builder, you can accomplish setting view's tag in the "Attributes Inspector" tab:

    enter image description here

    Don't forget to set userInteractionEnabled to YES. I left logical and direction verification up to you.