我在UITextView上使用 shouldChangeTextIn ,并且可以使用 shouldChangeTextIn 中的以下代码将TextView限制为最多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
但是,我想将两者结合起来,以便对它们进行检查,而我无法弄清楚。谁能指导我正确的方向?
最好的问候, 埃里克
答案 0 :(得分:2)
您应该存储布尔值而不是返回布尔值,并将其与&&
组合并返回。
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
}
答案 1 :(得分:0)
使用&&(和运算符)组合布尔值并返回结果
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
}