title: Keeping User-Input UITextVIew Content Constrained to Its Own Frame
body: <p>Trying to create a large textbox of fixed size.</p>
  
  <p>This problem is very similar to the 140 character constraint problem, but instead of stopping typing at 140 characters, I want to stop typing when the edge of the textView's frame is reached, instead of extending below into the abyss. Here is what I've got for the delegate method. Seems to always be off by a little bit. Any thoughts?</p>
  
  <pre><code>- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  {
      BOOL edgeBump = NO;
      CGSize constraint = textView.frame.size;
  
      CGSize size = [[textView.text stringByAppendingString:text] sizeWithFont:textView.font 
                                                             constrainedToSize:constraint 
                                                                 lineBreakMode:UILineBreakModeWordWrap];
      CGFloat height = size.height;
  
      if (height &gt; textView.frame.size.height) {
          edgeBump = YES;
      }
  
      if([text isEqualToString:@"\b"]){
          return YES;
      } else if(edgeBump){
          NSLog(@"EDGEBUMP!");
          return NO;
      }   
  
      return YES;
  }
  </code></pre>
  
  <p>EDIT: As per Max's suggestion below, here is the code that works (note, however, that autocorrect and cut do not work here):</p>
  
  <pre><code>- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  {
      CGSize constraint = textView.frame.size;
  
      NSString *whatWasThereBefore = textView.text;
  
      textView.text = [textView.text stringByReplacingCharactersInRange:range withString:text];
  
      if (textView.contentSize.height &gt;= constraint.height) {
          textView.text = whatWasThereBefore;
      }
  
      return NO;
  }
  </code></pre>