我在 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/