RCTSegmentedControl.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RCTSegmentedControl.h"
  8. #import "RCTConvert.h"
  9. #import "RCTEventDispatcher.h"
  10. #import "UIView+React.h"
  11. @implementation RCTSegmentedControl
  12. - (instancetype)initWithFrame:(CGRect)frame
  13. {
  14. if ((self = [super initWithFrame:frame])) {
  15. _selectedIndex = self.selectedSegmentIndex;
  16. [self addTarget:self action:@selector(didChange) forControlEvents:UIControlEventValueChanged];
  17. }
  18. return self;
  19. }
  20. - (void)setValues:(NSArray<NSString *> *)values
  21. {
  22. _values = [values copy];
  23. [self removeAllSegments];
  24. for (NSString *value in values) {
  25. [self insertSegmentWithTitle:value atIndex:self.numberOfSegments animated:NO];
  26. }
  27. super.selectedSegmentIndex = _selectedIndex;
  28. }
  29. - (void)setSelectedIndex:(NSInteger)selectedIndex
  30. {
  31. _selectedIndex = selectedIndex;
  32. super.selectedSegmentIndex = selectedIndex;
  33. }
  34. - (void)setBackgroundColor:(UIColor *)backgroundColor
  35. {
  36. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \
  37. __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  38. if (@available(iOS 13.0, *)) {
  39. [super setBackgroundColor:backgroundColor];
  40. }
  41. #endif
  42. }
  43. - (void)setTextColor:(UIColor *)textColor
  44. {
  45. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \
  46. __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  47. if (@available(iOS 13.0, *)) {
  48. [self setTitleTextAttributes:@{NSForegroundColorAttributeName : textColor} forState:UIControlStateNormal];
  49. }
  50. #endif
  51. }
  52. - (void)setTintColor:(UIColor *)tintColor
  53. {
  54. [super setTintColor:tintColor];
  55. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && defined(__IPHONE_13_0) && \
  56. __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0
  57. if (@available(iOS 13.0, *)) {
  58. [self setSelectedSegmentTintColor:tintColor];
  59. [self setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}
  60. forState:UIControlStateSelected];
  61. [self setTitleTextAttributes:@{NSForegroundColorAttributeName : tintColor} forState:UIControlStateNormal];
  62. }
  63. #endif
  64. }
  65. - (void)didChange
  66. {
  67. _selectedIndex = self.selectedSegmentIndex;
  68. if (_onChange) {
  69. _onChange(@{@"value" : [self titleForSegmentAtIndex:_selectedIndex], @"selectedSegmentIndex" : @(_selectedIndex)});
  70. }
  71. }
  72. @end