Skip to content

Instantly share code, notes, and snippets.

@mackross
Last active December 17, 2015 15:19
Show Gist options
  • Save mackross/5630857 to your computer and use it in GitHub Desktop.
Save mackross/5630857 to your computer and use it in GitHub Desktop.
RACBinding between UITextfield and a target that sends a signal when the text is changed programatically or using the keyboard.
- (RACSignal *)bindTextfield:(UITextField *)textField target:(id)target keypath:(NSString *)keypath
{
textField.text = [target valueForKey:keypath];
RACObservablePropertySubject *textFieldTextProperty = [RACObservablePropertySubject propertyWithTarget:textField keyPath:@keypath(textField,text)];
RACSignal *textFieldEdited = [textField rac_textSignal];
[[textFieldTextProperty binding] bindTo:[[RACObservablePropertySubject propertyWithTarget:target keyPath:keypath] binding]];
[target rac_deriveProperty:keypath from:[textFieldEdited skip:1]];
RACSignal *textValue = [[RACSignal merge:@[ textFieldEdited, textFieldTextProperty ]] distinctUntilChanged];
return textValue;
}
// Updated after discussion with @jspahrsummers - I like this more.
- (RACSignal *)bindTextfield:(UITextField *)textField target:(id)target keypath:(NSString *)keypath
{
RACPropertySubject *textProperty = [RACPropertySubject property];
RACBinding *textPropertyBinding = [textProperty binding];
[[textField rac_textSignal] subscribe:textPropertyBinding];
RACBind(textField, text) = textPropertyBinding;
[[textProperty binding] bindTo:[[RACObservablePropertySubject propertyWithTarget:target keyPath:keypath] binding]];
return [textProperty startWith:[target valueForKeyPath:keypath]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment