我正在创建一个应用程序,其中有一个UITextView,只允许用户键入2行文本。所以文本不会到达第三行,因为UITextView会要求它停止。有谁知道如何在Swift编程中处理这个问题?我发现有一种方法可以实现这一点,但是用Objective-C代码编写
- (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;
}
}
我一直在努力使用Swift中的等效代码,尤其是这行代码:
NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
我无法弄清楚如何在Swift中处理NSRange。有人可以帮助我吗?
答案 0 :(得分:-1)
您可以设置两行的帧大小并限制可以输入的字符总数吗?