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 ?