Limit the number of lines for UITextview
Maciek Czarnik answer does not worked for me, but it got me insights what to do.
iOS 7+
Swift
textView.textContainer.maximumNumberOfLines = 10
textView.textContainer.lineBreakMode = .byTruncatingTail
ObjC
textView.textContainer.maximumNumberOfLines = 10;
textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
Maybe this can help (iOS 7+):
textView.textContainer.maximumNumberOfLines = 10;
[textView.layoutManager textContainerChangedGeometry:textView.textContainer];
Even first line should do the trick I guess, but doesn't... Maybe its a bug in SDK
You have the right idea, but the wrong method. textView:shouldChangeTextInRange:replacementText:
is called whenever the text is going to change; you can access the current content of the text view using its text
property, and you can construct the new content from the passed range and replacement text with [textView.text stringByReplacingCharactersInRange:range withString:replacementText]
. You can then count the number of lines and return YES to allow the change or NO to reject it.
in Swift 3.0
version:
self.textView.textContainer.maximumNumberOfLines = self.textViewNumberOflines
self.textView.textContainer.lineBreakMode = .byTruncatingTail
Maciek Czarnik's answer does not seem to work for me, even in iOS7. It gives me strange behavior, I don't know why.
What I do to limit the number of lines in the UITextView is simply :
(tested only in iOS7) In the following UITextViewDelegate method :
- (void)textViewDidChange:(UITextView *)textView
{
NSUInteger maxNumberOfLines = 5;
NSUInteger numLines = textView.contentSize.height/textView.font.lineHeight;
if (numLines > maxNumberOfLines)
{
textView.text = [textView.text substringToIndex:textView.text.length - 1];
}
}