限制 UITextView 中的行数 [英] Limiting the number of lines within a UITextView
问题描述
我很清楚有人问过这个问题,但我找不到有效的答案.结合使用先前的解决方案,我想出了这个代码:
I'm well aware this question has been asked but I cannot find a valid answer. Using a combination of prior solutions I've come up with this code:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string
{
int numLines = notesTextView.contentSize.height / notesTextView.font.lineHeight;
if (numLines <= 8)
{
return true;
}
return false;
}
这行不通,因为行数是在附加文本之前计算的,所以我们仍然需要超出我们想要的行,然后被困在上面,因为无法进一步编辑.
This does not work because the number of lines is counted prior to the additional text so we are still taken a line beyond what we want and are then trapped on it as no further editing is possible.
我也尝试过检测\n"条目的解决方案,但这也不起作用,因为我们可以在不按回车的情况下自然地到达新行.
I've also tried solutions that detect "\n" entries but this doesn't work either as we can reach new lines naturally without pressing return.
推荐答案
我也遇到了这个问题.早期的解决方案都不适合我.这是我的解决方案,希望:(仅限 iOS 7+!)
I also encountered this problem. None of the earlier solutions worked well for me. Here is my solution, hope: (iOS 7+ only!)
- (void)textViewDidChange:(UITextView *)textView
{
NSLayoutManager *layoutManager = [textView layoutManager];
NSUInteger numberOfLines, index, numberOfGlyphs = [layoutManager numberOfGlyphs];
NSRange lineRange;
for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++)
{
(void) [layoutManager lineFragmentRectForGlyphAtIndex:index
effectiveRange:&lineRange];
index = NSMaxRange(lineRange);
}
if (numberOfLines > 3)
{
// roll back
_labelField.text = _text;
}
else
{
// change accepted
_text = _labelField.text;
}
}
它使用 NSString ivar _text 能够在文本更改后回滚.这不会导致任何闪烁.
It uses an NSString ivar _text to be able to roll back after the text has been changed. This does not cause any flickering.
numberOfLines 参考:https://developer.apple.com/library/mac/documentation/cocoa/conceptual/TextLayout/Tasks/CountLines.html#//apple_ref/doc/uid/20001810-CJBGBIBB
numberOfLines reference: https://developer.apple.com/library/mac/documentation/cocoa/conceptual/TextLayout/Tasks/CountLines.html#//apple_ref/doc/uid/20001810-CJBGBIBB
这篇关于限制 UITextView 中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!