我在UITExtVIEW中使用BoeDeCueTeExtIn,并且我可以使用SubDeCudieExtIn中的以下代码将TeXVIEW限制为最多4行或最多140个字符:
最多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

但是,我想把这两个结合起来,这样它就可以检查两个,而我无法找出答案。有人能指引我正确的方向吗?
谨致问候,
埃里克

最佳答案

您应该存储bool值而不是返回它,并将它们与&&组合并返回它。

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
}

关于ios - UITextView中最多4行和总共140个字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52407614/

10-11 14:43