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

标签 ios swift uitextview

我在 UITextView 上使用 shouldChangeTextIn 并且我可以在 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

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

最好的问候, 埃里克

最佳答案

您应该存储 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/

相关文章:

iphone - 如何将一个 AlertView 与另一个 AlertView 一起显示

python - Google App Engine (Python) 中的 AES 加密和 iOS (Objective-C) 中的解密

ios - 如何从 iOS 中的 CFStream 获取远程地址?

快速 Mac 操作系统 : make trackpad reflect display size for NSTouch events

ios - 如何知道文字的走向?

ios - 单击后重绘自定义 UIButton

ios - 为什么我的#selector 不工作?

ios - 如何关闭一行上的一个开关并打开另一行上的另一个开关

swift - 更新通过 Swift 3 中的 NSLayout 设置的 UITextView 大小