如何根据 UITextView 中的空行数禁用 UITextView 中的 return 键?

How can I disable the return key in a UITextView based on the number of empty rows in the UITextView?

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

如何做到这一点?

我知道如果光标所在的当前行是空的,如何防止使用 return 键,使用以下方法:

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 行为空,则阻止用户使用 return 键。

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

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

这看起来像这样:

let lastThreeCharacters = textView.text.suffix(3)

let lastThreeAreNewlines = (lastThreeCharacters.count == 3) && lastThreeCharacters.allSatisfy( {[=10=].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)
}

这可能需要针对边缘情况进行微调,但这肯定是我的起点。这个想法是用当前输入检查文本视图中的最后 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
}