带有 ReactiveCocoa 的 MVVM:限制视图模型中 UITextField 的文本长度 [英] MVVM with ReactiveCocoa: limit the text length of a UITextField in view model

查看:74
本文介绍了带有 ReactiveCocoa 的 MVVM:限制视图模型中 UITextField 的文本长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在采用带有 ReactiveCocoa 的 MVVM.现在我有一个 UITextField,我需要将它的最大文本长度限制为 100.

I'm adopting MVVM with ReactiveCocoa. Now I have a UITextField which I need to limit it's max text length to 100.

在我看来:

- (void)bindViewModel
{
    RAC(self.viewModel, text) = self.textField.rac_textSignal;
    [RACObserve(self.viewModel, text) subscribeNext:(NSString *text) {
        self.textField.text = text;
    }];
}

在我的视图模型中

- (id)init
{
    [RACObserve(self, text) subscribeNext:^(NSString *x) {
        //block 1
        if (x.length > maxTextLength) {
            x = [x substringToIndex:maxTextLength];
        }
    }];
}

但这不起作用,block 1 永远不会被调用.

But this doesn't work, block 1 is never called.

通过使用 MVVM,我认为文本长度控制逻辑应该放在我的视图模型中,但实现这一目标的正确方法是什么?

By using MVVM, I believe that the text length control logic should be put in my view model, but what is the proper way to achieve this?

推荐答案

这个答案中所述:你可以采取rac_textSignal 并使用 map 将字符串修剪为所需的长度.然后使用 RAC 宏将映射的信号绑定到文本字段.正如您所指出的,视图模型不应该引用视图.但是它可以传递一个信号并返回一个映射的信号.

As described in this answer: you can take rac_textSignal from the text field and use map to trim the string to the desired length. Then bind the mapped signal to the text field using RAC macro. As you noted, view model shouldn't have a reference to the view. But it can be passed a signal and return a mapped signal.

在视图中:

RAC(self.textField, text) = [self.viewModel validatedTextWithSignal:self.deviceName.rac_textSignal];

在您的视图模型中:

- (RACSignal *)validatedTextWithSignal:(RACSignal *)signal {
    NSUInteger kMaxLength = 5;
    return [signal map:^id(NSString *text) {
        return text.length <= kMaxLength ? text : [text substringToIndex:kMaxLength];
    }];
}

这也使文本控制逻辑易于测试 - 在单元测试中,您可以将诸如 -[RACSignal return:@"foo"] 之类的内容传递给视图模型并检查输出是否为正确.

This also makes the text control logic easy to test - in unit tests, you can pass something like -[RACSignal return:@"foo"] to the view model and check if the output is correct.

这篇关于带有 ReactiveCocoa 的 MVVM:限制视图模型中 UITextField 的文本长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆