UIButton+XYButton.m 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // UIButton+XYButton.m
  3. // MiAiApp
  4. //
  5. // Created by voidcat on 2017/6/1.
  6. // Copyright © 2017年 voidcat. All rights reserved.
  7. //
  8. #import "UIButton+XYButton.h"
  9. @implementation UIButton (XYButton)
  10. -(void)setBlock:(void(^)(UIButton*))block
  11. {
  12. objc_setAssociatedObject(self,@selector(block), block,OBJC_ASSOCIATION_COPY_NONATOMIC);
  13. [self addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
  14. }
  15. -(void(^)(UIButton*))block
  16. {
  17. return objc_getAssociatedObject(self,@selector(block));
  18. }
  19. -(void)addTapBlock:(void(^)(UIButton*))block
  20. {
  21. self.block= block;
  22. [self addTarget:self action:@selector(click:)forControlEvents:UIControlEventTouchUpInside];
  23. }
  24. -(void)click:(UIButton*)btn
  25. {
  26. if(self.block) {
  27. self.block(btn);
  28. }
  29. }
  30. - (void)setBadge:(NSString *)number andFont:(int)font{
  31. if (!number.integerValue) {
  32. UIView *view = [self viewWithTag:110];
  33. [view removeFromSuperview];
  34. return;
  35. }
  36. CGFloat width = self.bounds.size.width;
  37. CGSize size = [number textSizeIn:CGSizeMake(99, 99) font:[UIFont systemFontOfSize:font]];
  38. UILabel *badge = [[UILabel alloc] initWithFrame:CGRectMake(width*2/3, -width/4, width/2+(number.length-1)*size.width, width/2)];
  39. badge.text = number;
  40. badge.textAlignment = NSTextAlignmentCenter;
  41. badge.font = [UIFont systemFontOfSize:font];
  42. badge.backgroundColor = [UIColor redColor];
  43. badge.textColor = [UIColor whiteColor];
  44. badge.layer.cornerRadius = width/4;
  45. badge.layer.masksToBounds = YES;
  46. badge.tag = 110;
  47. [self addSubview:badge];
  48. }
  49. @end