ios - 带有 ReactiveCocoa 的 MVVM : limit the text length of a UITextField in view model

标签 ios objective-c mvvm reactive-cocoa

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

在我看来:

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

在我的 View 模型中

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

但这不起作用,block 1 从未被调用。

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

最佳答案

this answer 中所述:您可以从文本字段中获取 rac_textSignal 并使用 map 将字符串修剪为所需的长度。然后使用 RAC 宏将映射信号绑定(bind)到文本字段。 如您所述, View 模型不应引用 View 。但它可以传递一个信号并返回一个映射信号。

在 View 中:

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

在你的 View 模型中:

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

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

关于ios - 带有 ReactiveCocoa 的 MVVM : limit the text length of a UITextField in view model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228116/

相关文章:

c# - 将 wpf View 保存为图像,最好是 .png

html - 如何从 UILabel 中的 html 链接中删除下划线?

ios - 不能在 iOS 设备上只运行一个应用程序

ios - 后台模式下的 AVSpeechSynthesizer

iphone - 删除重复的 nsmutableArray

c# - 将字典绑定(bind)到 WPF 中的组合框显示不正确

ios - 将超链接添加到来自 iOS 应用程序的电子邮件中的预加载文本中

iphone - 在 Bump Api 发送图像方面需要一些帮助

IOS swift - objective-c 代码迁移到 swift

wpf - 如何使用 MVVM 处理 WPF 列表框 selectionchanged 事件