How to get n lines of text from UITextView in iOS

896 Views Asked by At

In my application i need to restrict to user enter 7 lines only in UITextView. When he tries enter text in 8 line we need to stop allowing editing and show an alert message. Its working fine by using CGSize of getting UITextView text.

But when user enters text in UITextView as Paste its not allowing if text is more than 7 lines. As per requirement i need to get the 7 lines of Text from entred (Copied & Pasted ) in to UITextView.

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string
    {
        NSString *temp = [textView.text stringByReplacingCharactersInRange:range withString:string]
        CGSize size = [temp sizeWithFont:textView.font constrainedToSize:CGSizeMake(textView.frame.size.width,999) lineBreakMode:UILineBreakModeWordWrap];
        int numLines = size.height / textView.font.lineHeight;
        if (numLines <= 8)
        {
            return true;
        }

//Alert
    return false;
}

Please help me in this issue. Thanks in Advance.

1

There are 1 best solutions below

0
On

You could use the UITextViewTextDidChangeNotification notification to alert you on other changes like text being pasted in. (referenced at the bottom of this page)

Or, there is also this handy category on UITextView that allows it to work with the UITextField UIControl events that can be found here.