CheckButton.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // CheckButton.m
  3. // CommonLibrary
  4. //
  5. // Created by Alexi on 14-1-19.
  6. // Copyright (c) 2014年 CommonLibrary. All rights reserved.
  7. //
  8. #import "CheckButton.h"
  9. #import "UIView+CustomAutoLayout.h"
  10. @implementation CheckButton
  11. - (void)setIsCheck:(BOOL)isCheck
  12. {
  13. _button.selected = isCheck;
  14. }
  15. - (BOOL)isCheck
  16. {
  17. return _button.selected;
  18. }
  19. - (void)onCheck
  20. {
  21. _button.selected = !_button.selected;
  22. if (_checkAction) {
  23. _checkAction(self);
  24. }
  25. }
  26. - (instancetype)initNormal:(UIImage *)image selectedImage:(UIImage *)simage title:(NSString *)title checkAction:(CheckButtonAction)action
  27. {
  28. if (self = [super init])
  29. {
  30. self.checkAction = action;
  31. __weak CheckButton *ws = self;
  32. self.button = [[MenuButton alloc] initWithTitle:nil icon:image action:^(id<MenuAbleItem> menu) {
  33. [ws onCheck];
  34. }];
  35. [self.button setImage:simage forState:UIControlStateSelected];
  36. [self.button setImage:simage forState:UIControlStateHighlighted];
  37. [self addSubview:_button];
  38. // if (title)
  39. // {
  40. self.title = [UILabel labelWithTitle:title];
  41. self.title.textAlignment = NSTextAlignmentCenter;
  42. [self addSubview:_title];
  43. // }
  44. UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onCheck)];
  45. [self addGestureRecognizer:ges];
  46. }
  47. return self;
  48. }
  49. - (BOOL)isSelected
  50. {
  51. return _button.isSelected;
  52. }
  53. #define kCheckSize CGSizeMake(20, 20)
  54. - (void)relayoutFrameOfSubViews
  55. {
  56. if (self.title)
  57. {
  58. CGRect rect = self.bounds;
  59. CGRect chectRect = rect;
  60. chectRect.size.width = chectRect.size.height;
  61. const CGSize kSize = kCheckSize;
  62. _button.frame = CGRectInset(chectRect, (chectRect.size.width - kSize.width)/2, (chectRect.size.height - kSize.height)/2);
  63. rect.origin.x += chectRect.size.width;
  64. rect.size.width -= chectRect.size.width;
  65. _title.frame = rect;
  66. }
  67. else
  68. {
  69. [_button sizeWith:kCheckSize];
  70. [_button layoutParentCenter];
  71. }
  72. }
  73. @end