0

I am making an application in which there is an UITextView that only allows users to type in 2 lines of text. So the text will not reach the third line as the UITextView would ask it to stop. Does anyone know how to approach this in Swift programming? I have found there is a way to achieve this but written in Objective-C code

- (BOOL) textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
     NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
_tempTextInputView.text = newText;

// Calcualte the number of lines with new text in temporary UITextView
CGRect endRectWithNewText = [_tempTextInputView caretRectForPosition:_tempTextInputView.endOfDocument];
CGRect beginRectWithNewText = [_tempTextInputView caretRectForPosition:_tempTextInputView.beginningOfDocument];
float beginOriginY = beginRectWithNewText.origin.y;
float endOriginY = endRectWithNewText.origin.y;
int numberOfLines = (endOriginY - beginOriginY)/textView.font.lineHeight + 1;

if (numberOfLines > maxLinesInTextView) {// Too many lines
    return NO;
}else{// Number of lines  will not over the limit
    return YES;
}

}

I have been struggling with the equivalent code in Swift especially this line of code:

NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];  

I just couldn't figure out how to deal with NSRange in Swift. Could someone please help me ?

The Mach System
  • 6,703
  • 3
  • 16
  • 20
  • I think this should work for that line: NSString *newText = textView.text.stringByReplacingCharactersInRange(range, withString: text) – rdelmar Oct 01 '14 at 04:12
  • @rdelmar: what do you mean by that? – The Mach System Oct 01 '14 at 04:14
  • You asked how to translate that one line into Swift. That's how you do it (assuming that you've already created range and text). – rdelmar Oct 01 '14 at 04:15
  • @rdelmar: Your comment before being edited was confusing. But this line gives me a syntax error textView.text.stringByReplacingCharactersInRange(range, withString: text) saying "nsrange is not convertible to range string.index" – The Mach System Oct 01 '14 at 04:19
  • 1
    I think you might have to create a variable for the textView's text (var theText = textView!.text as NSString), and use that instead of textView.text in the code I posted. – rdelmar Oct 01 '14 at 04:34
  • Check this link http://stackoverflow.com/questions/4172615/how-to-find-uilabels-number-of-lines – NANNAV Oct 01 '14 at 06:54

1 Answers1

-1

Can you just set the frame size for two lines and limit the total number of characters that can be entered?

Steve Rosenberg
  • 19,348
  • 7
  • 46
  • 53
  • That could do. But my app has multiple UITextViews so I'm afraid your approach is not quite practical in this case as I will need to count how many characters should be limited for every UITextView – The Mach System Oct 01 '14 at 04:12