繁体   English   中英

UITextFieldDelegate具有ReactiveCocoa的textFieldShouldReturn

[英]UITextFieldDelegate textFieldShouldReturn with ReactiveCocoa

我正在尝试使用ReactiveCocoa实现UITextFieldDelegate textFieldShouldReturn处理。 不幸的是,当我订阅信号时,subscribeNext块会运行。

使用委派的实现将是:

- (void)viewDidLoad
{
    ...
    self.myTextField.delegate = self;
}

...

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.myTextField) {
        NSLog(@"Let's go!");
    }

    return YES;
}

在ReactiveCocoa中,我以类似UITextView + RACSignalSupport的方式为UITextField添加了类别。

@implementation UITextField (RACKeyboardSupport)

static void RACUseDelegateProxy(UITextField *self)
{
    if (self.delegate == self.rac_delegateProxy) return;

    self.rac_delegateProxy.rac_proxiedDelegate = self.delegate;
    self.delegate = (id)self.rac_delegateProxy;
}

- (RACDelegateProxy *)rac_delegateProxy
{
    RACDelegateProxy *proxy = objc_getAssociatedObject(self, _cmd);
    if (proxy == nil) {
        proxy = [[RACDelegateProxy alloc] initWithProtocol:@protocol(UITextFieldDelegate)];
        objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    return proxy;
}

- (RACSignal *)rac_keyboardReturnSignal
{
    @weakify(self);
    RACSignal *signal = [[[[RACSignal
                            defer:^{
                                @strongify(self);
                                return [RACSignal return:RACTuplePack(self)];
                            }]
                           concat:[self.rac_delegateProxy signalForSelector:@selector(textFieldShouldReturn:)]]
                          takeUntil:self.rac_willDeallocSignal]
                         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]];

    RACUseDelegateProxy(self);

    return signal;
}

@end

即使从未按下回车键,在这里也会执行subscribeNext块:

- (void)viewDidLoad
{
    ...
    [self.myTextField.rac_keyboardReturnSignal subscribeNext:^(id x) {
        Log(@"Let's go with RAC!");
    }];
}

我必须使用skip:1来避免该问题:

- (void)viewDidLoad
{
    ...
    [[self.myTextField.rac_keyboardReturnSignal skip:1] subscribeNext:^(id x) {
        Log(@"Let's go with RAC!");
    }];
}

知道为什么会这样吗?

解:

- (RACSignal *)rac_keyboardReturnSignal
{
    RACSignal *signal = [[[self.rac_delegateProxy
                           signalForSelector:@selector(textFieldShouldReturn:)]
                          takeUntil:self.rac_willDeallocSignal]
                         setNameWithFormat:@"%@ -rac_keyboardReturnSignal", [self rac_description]];

    RACUseDelegateProxy(self);

    return signal;
}

您正在返回立即在你返回一个值的信号defer块,然后concat当-ing新值到流textFieldShouldReturn被调用。

UITextView+RACSignalSupport.m的代码正在调用reduceEach ,以返回从UITextView实例提取的字符串值。 defer仅用于具有在订阅时生成的初始值。

基本上,我不认为你需要的defer都为您的使用情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM