这是我过去的做法,希望能给你一些帮助。
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// limit the number of lines in textview
NSString* newText = [mytextView.text stringByReplacingCharactersInRange:range withString:text];
// pretend there's more vertical space to get that extra line to check on
CGSize tallerSize = CGSizeMake(mytextView.frame.size.width-15, mytextView.frame.size.height*2);
CGSize newSize = [newText sizeWithFont:mytextView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
if (newSize.height > mytextView.frame.size.height)
{
NSLog(@"two lines are full");
return NO;
}
// dismiss keyboard and send comment
if([text isEqualToString:@"\n"]) {
[mytextView resignFirstResponder];
return NO;
}
return YES;
}
祝你好运。
编辑:
好的,请尝试以下方法,看看这是否适合您。只需将行数更改为您想要的任何数字。
(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@"n"]) {
rows++;
if(rows >= maxNumberOfLines){
//Exit textview
return NO;
}
}
return YES;
让我知道这是否可行。