菜鸟教程小白 发表于 2022-12-12 13:12:59

ios - 如何绑定(bind) NSAttributeString(或 NSMutableAttributedString)


                                            <p><p>我想使用 MVVMCross 将属性字符串绑定(bind)到 UILabel。要绑定(bind)常规字符串,我会这样做:</p>

<pre><code>set.Bind(MyLabel).To(vm =&gt; vm.MyString);
</code></pre>

<p>但我需要一个字符串,其中部分文本将使用一种颜色和一种字体大小,而另一部分将使用不同的颜色和不同的字体大小。如果这是静态的,没问题,我会在界面生成器中添加一个标签并将其设置为“属性”,然后在我需要的字符串的哪个部分设置我想要的任何字体选项。</p>

<p>所以我认为使用 Mvvmcross,我可能需要一个转换器来将我的源字符串转换为属性字符串,所以我尝试从 <code>MvxValueConverter<string,NSMutableAttributedString></code> 创建一个转换器来执行此操作在其 <code>Convert</code> 方法中:</p>

<pre><code>return new NSMutableAttributedString(value);
</code></pre>

<p>最终我会添加一些不同的属性。不幸的是,这不起作用。如果我这样设置绑定(bind):</p>

<pre><code>set.Bind(MyLabel).To(vm =&gt; vm.MyString).WithConversion(&#34;MyConverter&#34;);
</code></pre>

<p>似乎 MvvmCross 只是对属性字符串执行了 <code>.ToString</code> 并显示为:</p>

<pre><code>Some Text {}
</code></pre>

<p>注意 <code>{}</code> 不是原始字符串的一部分。</p>

<p>有没有办法在 MVVMCross 中绑定(bind)属性字符串?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果你打电话</p>

<pre><code> set.Bind(MyLabel).To(vm =&gt; vm.MyString);
</code></pre>

<p>那么您将绑定(bind) UILabel 的默认属性,即 <code>string</code> 属性 Text。</p>

<p>您需要改为绑定(bind) AttributedText。尝试添加类似:</p>

<pre><code>    .For(l =&gt; l.AttributedText)
</code></pre>

<p>这里有一些关于使用 AttributedText 的问题 - 例如 <a href="https://stackoverflow.com/questions/15643232/underline-text-in-uilabel-in-monotouch-porting-objc-code" rel="noreferrer noopener nofollow">Underline text in UILabel in monotouch (porting ObjC code)</a> </p>

<p>有关 mvx 数据绑定(bind)的更多信息,请参阅 <a href="https://github.com/slodge/MvvmCross/wiki/Databinding" rel="noreferrer noopener nofollow">https://github.com/slodge/MvvmCross/wiki/Databinding</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何绑定(bind) NSAttributeString(或 NSMutableAttributedString),我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/17934294/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/17934294/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何绑定(bind) NSAttributeString(或 NSMutableAttributedString)