CustomSwitch.m 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // CustomSwitch.m
  3. // AIIM
  4. //
  5. // Created by qitewei on 2025/5/22.
  6. //
  7. #import "CustomSwitch.h"
  8. @implementation CustomSwitch
  9. - (instancetype)initWithFrame:(CGRect)frame {
  10. self = [super initWithFrame:frame];
  11. if (self) {
  12. [self commonInit];
  13. }
  14. return self;
  15. }
  16. - (instancetype)initWithCoder:(NSCoder *)coder {
  17. self = [super initWithCoder:coder];
  18. if (self) {
  19. [self commonInit];
  20. }
  21. return self;
  22. }
  23. - (void)commonInit {
  24. self.offBackgroundColor = [UIColor lightGrayColor];
  25. [self addTarget:self action:@selector(updateAppearance) forControlEvents:UIControlEventValueChanged];
  26. [self updateAppearance];
  27. }
  28. - (void)setOffBackgroundColor:(UIColor *)offBackgroundColor {
  29. _offBackgroundColor = offBackgroundColor;
  30. [self updateAppearance];
  31. }
  32. - (void)updateAppearance {
  33. if (self.isOn) {
  34. self.backgroundColor = self.onTintColor;
  35. } else {
  36. self.backgroundColor = self.offBackgroundColor;
  37. }
  38. self.layer.cornerRadius = CGRectGetHeight(self.bounds) / 2.0;
  39. self.clipsToBounds = YES;
  40. }
  41. - (void)layoutSubviews {
  42. [super layoutSubviews];
  43. [self updateAppearance];
  44. }
  45. @end