YYControl.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. //
  2. // YYControl.m
  3. // YYKitExample
  4. //
  5. // Created by ibireme on 15/9/14.
  6. // Copyright (c) 2015 ibireme. All rights reserved.
  7. //
  8. #import "YYControl.h"
  9. #import "YYKit.h"
  10. @implementation YYControl {
  11. UIImage *_image;
  12. CGPoint _point;
  13. NSTimer *_timer;
  14. BOOL _longPressDetected;
  15. }
  16. - (void)setImage:(UIImage *)image {
  17. _image = image;
  18. self.layer.contents = (id)image.CGImage;
  19. }
  20. - (void)dealloc {
  21. [self endTimer];
  22. }
  23. - (UIImage *)image {
  24. id content = self.layer.contents;
  25. if (content != (id)_image.CGImage) {
  26. CGImageRef ref = (__bridge CGImageRef)(content);
  27. if (ref && CFGetTypeID(ref) == CGImageGetTypeID()) {
  28. _image = [UIImage imageWithCGImage:ref scale:self.layer.contentsScale orientation:UIImageOrientationUp];
  29. } else {
  30. _image = nil;
  31. }
  32. }
  33. return _image;
  34. }
  35. - (void)startTimer {
  36. [_timer invalidate];
  37. _timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(timerFire) userInfo:nil repeats:NO];
  38. [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
  39. }
  40. - (void)endTimer {
  41. [_timer invalidate];
  42. _timer = nil;
  43. }
  44. - (void)timerFire {
  45. [self touchesCancelled:[NSSet set] withEvent:nil];
  46. _longPressDetected = YES;
  47. if (_longPressBlock) _longPressBlock(self, _point);
  48. [self endTimer];
  49. }
  50. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  51. _longPressDetected = NO;
  52. if (_touchBlock) {
  53. _touchBlock(self, YYGestureRecognizerStateBegan, touches, event);
  54. }
  55. if (_longPressBlock) {
  56. UITouch *touch = touches.anyObject;
  57. _point = [touch locationInView:self];
  58. [self startTimer];
  59. }
  60. }
  61. - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  62. if (_longPressDetected) return;
  63. if (_touchBlock) {
  64. _touchBlock(self, YYGestureRecognizerStateMoved, touches, event);
  65. }
  66. [self endTimer];
  67. }
  68. - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  69. if (_longPressDetected) return;
  70. if (_touchBlock) {
  71. _touchBlock(self, YYGestureRecognizerStateEnded, touches, event);
  72. }
  73. [self endTimer];
  74. }
  75. - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
  76. if (_longPressDetected) return;
  77. if (_touchBlock) {
  78. _touchBlock(self, YYGestureRecognizerStateCancelled, touches, event);
  79. }
  80. [self endTimer];
  81. }
  82. @end