【问题标题】:How can I disable the return key in a UITextView based on the number of empty rows in the UITextView?如何根据 UITextView 中的空行数禁用 UITextView 中的返回键?
【发布时间】:2022-01-23 19:34:26
【问题描述】:

TikTok 和 Instagram (iOS) 都在其编辑个人资料传记代码中内置了一种机制,使用户能够使用返回键并在用户个人资料传记中创建分隔线。但是,在返回一定数量的行后,行中没有文本,它们会阻止用户再次使用返回键。

如何做到这一点?

如果光标所在的当前行为空,我了解如何防止使用返回键,方法如下:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
  guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
    return false
  }
  return true

此外,我需要帮助弄清楚如何检测,例如,4 行是空的,并说明如果 4 行是空的,阻止用户使用返回键。

【问题讨论】:

  • 这里已经问过同样的问题:- stackoverflow.com/questions/29587912/…
  • 4 个连续的空行还是正文中任意位置的 4 个空行?
  • 连续@liquid
  • 请记住,如果用户粘贴一个包含 5 个连续空行的文本块,您必须单独处理这种情况。在那种情况下,我可能会在返回真假之前检查text 是否包含"\n\n\n\n\n" 或类似的东西。

标签: ios swift uitextview swift5


【解决方案1】:

这可能需要针对边缘情况进行微调,但这肯定是我的起点。这个想法是用当前输入检查文本视图的最后 4 个输入,并决定如何处理它。此特定代码将阻止用户创建第四个连续的空行。

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n",
       textView.text.hasSuffix("\n\n\n\n") {
        return false
    }
    return true
}

【讨论】:

    【解决方案2】:

    我不完全确定我是否正确理解了您的问题。但让我试着帮忙。

    UITextView 具有您可以读取的 text 属性。然后,如果用户输入新字符/插入新文本(确保使用复制粘贴文本进行测试),您可以检查文本的最后三个字符是否为换行符。如果是这样,并且用户正在尝试添加另一个换行符,您知道返回 false

    看起来像这样:

    let lastThreeCharacters = textView.text.suffix(3)
    
    let lastThreeAreNewlines = (lastThreeCharacters.count == 3) && lastThreeCharacters.allSatisfy( {$0.isNewline} ) // Returns true if the last 3 characters are newlines
    

    您需要实施一些额外的检查。将要插入的字符是换行符吗?如果用户粘贴文本,最后 4 个字符会是换行符吗?

    另一种方法是使用UITextViewDelegate 的另一种方法。您还可以实现textViewDidChange(_:),它在用户更改文本之后调用。然后,检查文本是否(以及在哪里)包含四个新行并将它们替换为空字符。

    这看起来像这样 (taken from here):

    func textViewDidChange(_ textView: UITextView) {
        // Avoid new lines also at the beginning
        textView.text = textView.text.replacingOccurrences(of: "^\n", with: "", options: .regularExpression)
        // Avoids 4 or more new lines after some text
        textView.text = textView.text.replacingOccurrences(of: "\n{4,}", with: "\n\n\n", options: .regularExpression)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2011-12-31
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 2014-03-30
      相关资源
      最近更新 更多