Skip to content

Commit

Permalink
Fix recycling of Switch
Browse files Browse the repository at this point in the history
Reviewed By: shergin

Differential Revision: D17714863

fbshipit-source-id: 8a90a08328f007c782689b4e711d252bd2e22538
  • Loading branch information
sammy-SC authored and facebook-github-bot committed Oct 3, 2019
1 parent eb08b42 commit a261e6d
Showing 1 changed file with 17 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,38 @@

@implementation RCTSwitchComponentView {
UISwitch *_switchView;
BOOL _wasOn;
}

- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
static const auto defaultProps = std::make_shared<const SwitchProps>();
_props = defaultProps;

_switchView = [[UISwitch alloc] initWithFrame:self.bounds];

[_switchView addTarget:self action:@selector(onChange:) forControlEvents:UIControlEventValueChanged];

_switchView.on = defaultProps->value;

self.contentView = _switchView;

[self setPropsToDefault];
}

return self;
}

- (void)setPropsToDefault
{
static const auto defaultProps = std::make_shared<const SwitchProps>();
_props = defaultProps;
_switchView.on = defaultProps->value;
}

#pragma mark - RCTComponentViewProtocol

- (void)prepareForRecycle
{
[super prepareForRecycle];
[self setPropsToDefault];
}

+ (ComponentDescriptorProvider)componentDescriptorProvider
{
return concreteComponentDescriptorProvider<SwitchComponentDescriptor>();
Expand All @@ -51,7 +60,6 @@ - (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &
// `value`
if (oldSwitchProps.value != newSwitchProps.value) {
_switchView.on = newSwitchProps.value;
_wasOn = newSwitchProps.value;
}

// `disabled`
Expand Down Expand Up @@ -79,10 +87,10 @@ - (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &

- (void)onChange:(UISwitch *)sender
{
if (_wasOn == sender.on) {
const auto &props = *std::static_pointer_cast<const SwitchProps>(_props);
if (props.value == sender.on) {
return;
}
_wasOn = sender.on;

std::dynamic_pointer_cast<const SwitchEventEmitter>(_eventEmitter)
->onChange(SwitchOnChangeStruct{.value = static_cast<bool>(sender.on)});
Expand Down

0 comments on commit a261e6d

Please sign in to comment.