简体   繁体   English

如何将NSString绑定到Reactive Cocoa中的UITextView?

[英]How do I bind an NSString to a UITextView in Reactive Cocoa?

I'm building an iOS social client, and in the "compose" view, I've got a UITextView where the user enters text. 我正在构建一个iOS社交客户端,在“撰写”视图中,我有一个UITextView ,用户可以在其中输入文本。 I'd like to use ReactiveCocoa to bind the text of the UITextView to the NSString of the data model, to follow MVVM. 我想使用ReactiveCocoa将UITextViewtext绑定到数据模型的NSString ,以遵循MVVM。

However, I'm running into several issues, all related to a single thing: the RACObserve block doesn't get called when the UITextView 's text is changed programmatically. 但是,我遇到了几个问题,所有这些都与一件事有关:当以编程方式更改UITextView的文本时,不会调用RACObserve块。

(An example: I change the text into an attributed string to highlight #hashtags, @usernames, etc, but this attributed string doesn't get created when the view is programmatically changed.) (示例:我将文本更改为属性字符串以突出显示#hashtags,@ usernames等,但是当以编程方式更改视图时,不会创建此属性字符串。)

In my previous question on this topic , I got some helpful advice that I should bind the textview to the model - and vice versa - but it's not clear to me how I should do it with the current version of Reactive Cocoa. 有关该主题的上一个问题中 ,我得到了一些有用的建议,即应该将textview绑定到模型(反之亦然),但是我不清楚如何使用当前版本的Reactive Cocoa来做到这一点。 The sample code that I've managed to find calls APIs that are now deprecated. 我设法找到示例代码调用了现已弃用的API。

What's the appropriate way to bind the rac_textSignal of a UITextView to an NSString (and vice versa) so that I can reliably call a block of code when the contents of the UITextView are changed (whether programmatically or by the user)? UITextViewrac_textSignal绑定到NSString (反之亦然)的合适方法是rac_textSignal ,以便当UITextView的内容更改时(无论是通过编程方式还是由用户),我都能可靠地调用代码块?

The answer depends on whether the binding between the view model's text and the UITextView s text needs to be bidirectional. 答案取决于视图模型的textUITextViewtext之间的绑定是否需要双向。 Generally we try to stay away from bidirectional bindings because they become harder to reason about. 通常,我们试图远离双向绑定,因为它们变得难以推理。 Ideally only one direction is driving the data. 理想情况下,只有一个方向在驱动数据。

So in that case, you'd write something like: 因此,在这种情况下,您将编写如下内容:

RAC(self.viewModel, text) = [RACSignal merge:@[ 
                                [self.textView rac_textSignal], 
                                RACObserve(self.textView, text),
                            ]];

That way you're picking up on changes to both the UITextView s text property directly, and text changes that come from the user typing. 这样,您既可以直接对UITextViewtext属性进行更改,也可以对用户键入的文本进行更改。

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

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