Reputation: 57
I need to restrict my textview to only 6 lines. How do I limit my textview to 6 lines? I have put some character limit of 50 characters anyways.
Upvotes: 4
Views: 5901
Reputation: 387
for swift 4 this one worked for without any bugs:
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
return linesAfterChange <= textView.textContainer.maximumNumberOfLines
}
and if you want to limit characters also:
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
if(text == "\n") {
return linesAfterChange <= textView.textContainer.maximumNumberOfLines
}
let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
let numberOfChars = newText.count
return numberOfChars <= 30 // 30 characters limit
}
}
don't forget to add how many lines you want the limit to be in viewDidLoad
:
txtView.textContainer.maximumNumberOfLines = 2
Upvotes: 0
Reputation: 3956
That is rarely simple to achieve. Try out following code
inputTextView.textContainer.maximumNumberOfLines = 6
inputTextView.textContainer.lineBreakMode = .ByWordWrapping
Upvotes: 11