UITextView 最多 4 行且总共 140 个字符

Max 4 lines AND a total of 140 characters in UITextView

我在 UITextView 上使用 shouldChangeTextIn,我可以使用 [=] 中的以下代码将 TextView 限制为最多 4 行或最多 140 个字符22=]shouldChangeTextIn:

最多 4 行:

    let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
    let newLines = text.components(separatedBy: CharacterSet.newlines)
    let linesAfterChange = existingLines.count + newLines.count - 1

    return linesAfterChange <= textView.textContainer.maximumNumberOfLines

最多 140 个字符:

    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)

    return newText.utf16.count < 140

但是,我想将这两者结合起来,以便它检查两者,但我无法弄清楚。谁能指导我正确的方向?

此致, 埃里克

您应该存储布尔值而不是 return 并将它们与 && 和 return 结合起来。

let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
let newLines = text.components(separatedBy: CharacterSet.newlines)
let linesAfterChange = existingLines.count + newLines.count - 1
let linesCheck = linesAfterChange <= textView.textContainer.maximumNumberOfLines

let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let characterCountCheck = newText.utf16.count < 140

return linesCheck && characterCountCheck

旁注: 避免在 Swift 中使用 NSString。你可以用 String.

做同样的事情
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if let textViewString = textView.text, let range = Range(range, in: textViewString) {
        let newString = textViewString.replacingCharacters(in: range, with: text)
    }
    return condition
}

将布尔值与 &&(和运算符)相结合,return 结果

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        let existingLines = textView.text.components(separatedBy: CharacterSet.newlines)
        let newLines = text.components(separatedBy: CharacterSet.newlines)
        let linesAfterChange = existingLines.count + newLines.count - 1

        let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)

        return linesAfterChange <= textView.textContainer.maximumNumberOfLines && newText.utf16.count < 140
    }