您需要实现
textView:shouldChangeTextInRange:replacementText:
方法。每当文本将要更改时,都会调用此方法。您可以使用其 text 属性访问文本视图的当前内容。
使用
[textView.text stringByReplacingCharactersInRange:range withString:replacementText]
从传递的范围和替换文本构造新内容。
然后,您可以计算行数并返回
YES
以允许更改或
NO
以拒绝更改。
编辑:根据 OP 请求:
Swift:
func sizeOfString (string: String, constrainedToWidth width: Double, font: UIFont) -> CGSize {
return (string as NSString).boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font],
context: nil).size
}
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
var textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset))
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;
let boundingRect = sizeOfString(newText, constrainedToWidth: Double(textWidth), font: textView.font!)
let numberOfLines = boundingRect.height / textView.font!.lineHeight;
return numberOfLines <= 2;
}
Objective-C
- (CGSize) sizeOfString:(NSString*)str constrainedToWidth:(CGFloat)width andFont:(UIFont*)font
{
return [str boundingRectWithSize:CGSizeMake(width, DBL_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: font}
context:nil].size;
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
CGFloat textWidth = CGRectGetWidth(UIEdgeInsetsInsetRect(textView.frame, textView.textContainerInset));
textWidth -= 2.0 * textView.textContainer.lineFragmentPadding;
CGSize boundingRect = [self sizeOfString:newText constrainedToWidth:textWidth andFont:textView.font];
int numberOfLines = boundingRect.height / textView.font.lineHeight;
return numberOfLines <= 2;
}