title: iPhone: Limiting text input in an UITextView
body: <p>I am trying to limit the amount of LINES a user can have in an UITextView. Let's consider I only want to allow 4 lines (i.e. in the following example, you can't go higher than a height of 84 pixels with the given font in a given UITextView with a width of 200).</p>
  
  <p>I coded this to achieve the limiting and it works fine:</p>
  
  <pre><code>    - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText {
  
      NSString* newText = [aTextView.text stringByReplacingCharactersInRange:aRange withString:aText];
  
  
      CGSize strSize = [newText sizeWithFont:textView.font constrainedToSize:CGSizeMake(200, 10000) lineBreakMode:UILineBreakModeWordWrap];
  
  if (strSize.height &gt; 100)
  
      {
  
          return NO; // can't enter more text
      }
      else
          return YES; // let the textView know that it should handle the inserted text
      }
  </code></pre>
  
  <p>So far so good. The problem starts when I try to be sneaky and enter as many 'x's as I can before each return. In that case, I can get an extra of 4 lines... which I obviously do not want to allow. I assume that this has something to do with the lineBreakMode? Is there any case to alter this? I haven't found much in the docs (but then again, I usually have a hard time understanding them).</p>
  
  <p>I attached a couple of screenshots to illustrate the problem. I'd be grateful for any suggestions. Thanks a lot!</p>
  
  <hr>
  
  <p><img src="https://i.stack.imgur.com/dvYPX.png" alt="Normal behaviour - stops after 4 lines">
  <img src="https://i.stack.imgur.com/uBhat.png" alt="Deviant behaviour - too many lines through additional x-es"></p>