gpt4 book ai didi

swift - 防止用户在 UITextView 中输入多个新行

转载 作者:行者123 更新时间:2023-11-28 07:18:39 24 4
gpt4 key购买 nike

我有一个 UITextView 用户可以输入很多文本(大约 500 个字符)。

我想阻止用户提交表单,例如,如果它只是充满空的新行。

我尝试添加这个 -

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

这阻止了他们一遍又一遍地按回车键,但它也停止了文本换行。

我如何去除文本正文以便删除多个新行或首先阻止它们?

最佳答案

当文本字段完成编辑或将被提交时,您可以像这样使用 CharacterSet 删除所有空格和换行符:

let myString = "  Hello world  "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)

这将删除 Hello World 周围的空格,但不会删除中间的空格。

您所要做的就是在使用数据之前使用 textView.text != "" 检查文本不等于空字符串。

关于swift - 防止用户在 UITextView 中输入多个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58827424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com