菜鸟教程小白 发表于 2022-12-11 20:31:00

ios - shouldChangeCharactersIn 结合建议文本


                                            <p><p>我有一个 <code>UITextField</code> 并且正在使用委托(delegate)方法 <code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool</code></p>

<p>此处的字段可以显示建议的文本(例如姓名)。当提出建议与用户输入单个字母时,问题就出现了。如果采纳了建议(例如 Tom),则委托(delegate)方法会触发,但 <code>string</code> 只包含一个空格“”。这会导致验证失败,因为假设用户在实际选择了一个完整的单词时正在输入一个空白区域。 </p>

<p>我们如何使用 <code>shouldChangeCharactersIn</code> 来检查文本输入,但仍然允许使用建议的文本? </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果用户使用建议,<code>shouldChangeCharactersIn</code> 最多触发两次:第一次使用单个空格。然后,如果该方法返回 <code>false</code> 则不会发生其他任何事情。但是,如果该方法返回 <code>true</code> 则 <code>shouldChangeCharactersIn</code> 会在其末尾使用建议的字符串 + 空格触发更多。因此,如果您想使用键盘建议,您必须允许空格并(如果需要)稍后根据您的要求以某种方式删除它们。一种方法是像这样使用 <code>defer</code> (未经测试,但给你一个想法):</p>

<pre class="lang-swift prettyprint-override"><code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -&gt; Bool {
if string == &#34; &#34; {
    defer {
      if let text = textField.text, let textRange = Range(range, in: text) {
    textField.text = text.replacingCharacters(in: textRange, with: &#34;&#34;)
      }
    }
    return true
}

// rest of the code for input filtering

return false
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - shouldChangeCharactersIn 结合建议文本,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/52131894/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/52131894/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - shouldChangeCharactersIn 结合建议文本