Last active
August 29, 2015 13:57
-
-
Save seanwoodward/9550315 to your computer and use it in GitHub Desktop.
Auto-incrementing a value with UIButton and NSTimer or just use UIStepper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface ViewController | |
@property (nonatomic, weak) IBOutlet UILabel *numberLabel; | |
@property (nonatomic, strong) NSTimer *numberTimer; | |
@property (nonatomic, assign) double value; | |
@property (nonatomic, assign) BOOL cancelTimer; | |
@property (nonatomic, assign) NSTimeInterval timeInterval; | |
- (void)updateNumberLabel; | |
- (void)stopTimer; | |
- (IBAction)longPress:(id)sender; | |
- (IBAction)touchUpInside:(id)sender; | |
- (IBAction)touchDragExit:(id)sender; | |
- (IBAction)touchCancel:(id)sender; | |
@end | |
@implementation ViewController | |
- (void)updateNumberLabel | |
{ | |
self.numberLabel.text = [NSString stringWithFormat:@"%d", [@(self.value) intValue]]; | |
} | |
- (void)stopTimer | |
{ | |
self.cancelTimer = YES; | |
if (self.numberTimer) { | |
[self.numberTimer invalidate]; | |
self.numberTimer = nil; | |
self.timeInterval = 0; | |
} | |
[self updateNumberLabel]; | |
} | |
- (IBAction)addNumber:(id)sender | |
{ | |
NSTimeInterval newInterval = self.timeInterval ?: 1; | |
if (self.numberTimer) { | |
newInterval = MAX(0.02, newInterval - newInterval * 0.2); | |
} | |
if (self.cancelTimer) { | |
[self stopTimer]; | |
return; | |
} | |
self.value += 1; | |
[self updateNumberLabel]; | |
self.timeInterval = newInterval; | |
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:newInterval target:self selector:@selector(addNumber:) userInfo:nil repeats:NO]; | |
self.numberTimer = timer; | |
} | |
- (IBAction)longPress:(id)sender | |
{ | |
UILongPressGestureRecognizer *gr = (UILongPressGestureRecognizer *)sender; | |
CGPoint touchLocation = [gr locationInView:self.view]; | |
BOOL touchInButton = CGRectContainsPoint(gr.view.frame, touchLocation); | |
if (!self.numberTimer && touchInButton) { | |
self.cancelTimer = NO; | |
[self addNumber:nil]; | |
} | |
} | |
- (IBAction)touchUpInside:(id)sender | |
{ | |
[self stopTimer]; | |
} | |
- (IBAction)touchDragExit:(id)sender | |
{ | |
[self stopTimer]; | |
} | |
- (IBAction)touchCancel:(id)sender { | |
[self stopTimer]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment