سؤال

I've UITextField, UIImageView and UIButton in my UIView.

I've a RACSignal that prints the textbox field value using NSLog upon subscription. Also, the UIImageView acts as an error indicator.

The code snippet is shown below:

[username.rac_textSignal subscribeNext:^(NSString *value) {
    NSLog(@"-Text field(username) has been updated: %@", value);
}];

RAC(nameIndicator,image) = [username.rac_textSignal map:^id(NSString *value) {
                                NSLog(@"Text field(username) has been updated: %@", value);
                                if([value length]) return [UIImage imageNamed:@"GreenStar"];
                                else return [UIImage imageNamed:@"RedStar"];
                            }];

[[resetButton rac_signalForControlEvents:UIControlEventTouchUpInside]
 subscribeNext:^(id x) {
             [username setText:@""];
 }];

Whenever I reset the field using reset button the text-field gets cleared but the corresponding change in the nameIndicator is not reflected. However, if I reset the field using the backspace key the nameIndicator is turned from GreenStar.png to RedStar.png

Can anyone suggest me the correction required to reset the textfield along with nameIndicator image?

هل كانت مفيدة؟

المحلول

The signal you get from -rac_textSignal only reflects updates from the UI, not programmatic changes like -setText:.

The simple, imperative fix is to just assign nameIndicator.image in resetButton's subscribe block.

[[resetButton
    rac_signalForControlEvents:UIControlEventTouchUpInside]
    subscribeNext:^(id x) {
        username.text = @"";
        nameIndicator.image = [UIImage imageNamed:@"RedStar"];
    }];

Alternatively, a more functional solution is to create a signal that represents both direct changes to the text field and button taps that clear the text field. The latter signal will sends the empty string when the reset button is tapped, while also clearing the text field.

RACSignal *resetUsernameSignal = [[[resetButton
    rac_signalForControlEvents:UIControlEventTouchUpInside]
    mapReplace:@""]
    doNext:^(NSString *text) {
        username.text = text;
    }];

RAC(nameIndicator, image) = [[RACSignal
    merge:@[
        username.rac_textSignal,
        resetUsernameSignal
    ]]
    map:^(NSString *text) {
        NSLog(@"Text field(username) has been updated: %@", value);
        if([value length]) return [UIImage imageNamed:@"GreenStar"];
        else return [UIImage imageNamed:@"RedStar"];
    }]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top