UIButton+EnlargeTouchArea.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // UIButton+EnlargeTouchArea.m
  3. // wolfman
  4. //
  5. // Created by 张灿 on 2017/7/12.
  6. // Copyright © 2017年 shareSmile. All rights reserved.
  7. //
  8. #import "UIButton+EnlargeTouchArea.h"
  9. #import <objc/runtime.h>
  10. @implementation UIButton (EnlargeTouchArea)
  11. static char topNameKey;
  12. static char rightNameKey;
  13. static char bottomNameKey;
  14. static char leftNameKey;
  15. - (void)setEnlargeEdge:(CGFloat) size
  16. {
  17. objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
  18. objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
  19. objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
  20. objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:size], OBJC_ASSOCIATION_COPY_NONATOMIC);
  21. }
  22. - (void) setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left
  23. {
  24. objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
  25. objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
  26. objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
  27. objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
  28. }
  29. - (CGRect) enlargedRect
  30. {
  31. NSNumber* topEdge = objc_getAssociatedObject(self, &topNameKey);
  32. NSNumber* rightEdge = objc_getAssociatedObject(self, &rightNameKey);
  33. NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
  34. NSNumber* leftEdge = objc_getAssociatedObject(self, &leftNameKey);
  35. if (topEdge && rightEdge && bottomEdge && leftEdge)
  36. {
  37. return CGRectMake(self.bounds.origin.x - leftEdge.floatValue,
  38. self.bounds.origin.y - topEdge.floatValue,
  39. self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue,
  40. self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue);
  41. }
  42. else
  43. {
  44. return self.bounds;
  45. }
  46. }
  47. - (UIView*) hitTest:(CGPoint) point withEvent:(UIEvent*) event
  48. {
  49. CGRect rect = [self enlargedRect];
  50. if (CGRectEqualToRect(rect, self.bounds))
  51. {
  52. return [super hitTest:point withEvent:event];
  53. }
  54. return CGRectContainsPoint(rect, point) ? self : nil;
  55. }
  56. @end