以下は、'\n' + 折り返された行のサポートで機能します。
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.AutoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.AutocorrectionType = UITextAutocorrectionTypeNo;
self.KeyboardAppearance = UIKeyboardAppearanceAlert;
self.font = [UIFont fontWithName:@"Avenir" size:14];
self.maximumNumberOfLinesAllowed = 4;
self.delegate = self;
}
return self;
}
- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText
{
NSMutableString *t = [NSMutableString stringWithString: self.text];
[t replaceCharactersInRange: aRange withString: aText];
// First check for standard '\n' (newline) type characters.
NSUInteger numberOfLines = 0;
for (NSUInteger i = 0; i < t.length; i++) {
if ([[NSCharacterSet newlineCharacterSet] characterIsMember: [t characterAtIndex: i]]) {
numberOfLines++;
}
}
if (numberOfLines >= self.maximumNumberOfLinesAllowed)
return NO;
// Now check for word wrapping onto newline.
NSAttributedString *t2 = [[NSAttributedString alloc]
initWithString:[NSMutableString stringWithString:t] attributes:@{NSFontAttributeName:self.font}];
__block NSInteger lineCount = 0;
CGFloat maxWidth = self.frame.size.width;
NSLog(@"maxWidth = %.02f", maxWidth);
NSTextContainer *tc = [[NSTextContainer alloc] initWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)];
NSLayoutManager *lm = [[NSLayoutManager alloc] init];
NSTextStorage *ts = [[NSTextStorage alloc] initWithAttributedString:t2];
[ts addLayoutManager:lm];
[lm addTextContainer:tc];
[lm enumerateLineFragmentsForGlyphRange:NSMakeRange(0,lm.numberOfGlyphs)
usingBlock:^(CGRect rect,
CGRect usedRect,
NSTextContainer *textContainer,
NSRange glyphRange,
BOOL *stop)
{
lineCount++;
}];
// NSLog(@"%d", lineCount);
return (lineCount <= self.maximumNumberOfLinesAllowed);
}