CyberK
CyberK

Reputation: 1578

Swipe UILabel to alpha 0

I have a label, which I want to "swipe to delete". What I want is:

Any idea what the best way to implement this is?

Thanks in advance!

Upvotes: 0

Views: 302

Answers (2)

Gavin
Gavin

Reputation: 8200

You'll want to use a UIPanGestureRecognizer to do this. When the gesture recognizer starts, you'll want to keep track of the starting point. You'll also want to define some amount to pan over that is considered all the way over. As the pan happens, you'll see how far over your touch has moved and move the label by that amount. You'll also determine what percentage of the way over that you've moved thru your "all the way over" distance, and set the alpha accordingly.

Once you reach the spot, you can cancel the gesture recognizer (setting its enabled property to NO) and do whatever you want to do at that point. If the user releases their touch (so the gesture recognizer ends before they drag all of the way) you'll obviously want to reset the label position and alpha at that point.

You may also want to take into account the velocity of the pan at the time it ends, and if it's over a certain velocity, go ahead and make it continue animating to the finished state at that velocity, otherwise if it's not fast enough, make it animate back to the starting state. But you may want to only bother with this after you initially implement it to see if you want this or not.

Upvotes: 2

Pwner
Pwner

Reputation: 3795

Put this in your UIViewController.

WARNING: I typed all this without XCode and never tested it. You may need to fix spelling errors and adjust numbers.

// Declare this in the anonymous category of your UIViewController
@property(nonatomic, strong) UILabel* label;
- (void)didSwipeLabel:(UISwipeGestureRecognizer*)swipe;
- (void)willRemoveLabel;

// Put the following in the usual places in .m file
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label = [UILabel alloc] init];
    self.label.font = [UIFont boldSystemFontOfSize:30.0];
    self.label.text = @"SWIPE THIS LABEL TO CHANGE THE ALPHA";
    [self.label sizeToFit];
    [self.label addGestureRecognizer:[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipeLabel:)]];
    [self.view addSubview:self.label];
}

- (void)didSwipeLabel:(UISwipeGestureRecognizer*)swipe
{
    // The value of 0.1 needs to be adjusted. Most likely it needs
    // to be decreased.
    if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
        self.label.alpha = self.label.alpha - 0.1;
    } else if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
        self.label.alpha = self.label.alpha + 0.1;
    }

    if (self.label.alpha <= 0.0) {
        [self willRemoveLabel];
    }
}

- (void)willRemoveLabel
{
    NSLog(@"label should be removed");
}

Upvotes: 0

Related Questions