我正在使用UITextView
在我的视图中,我要求使用以下函数计算textview am包含的行数以读取'\n'
。但是这只有在从键盘按下返回键时才起作用,但是在线条换行器中(当我键入连续字符时,我不会获得新行字符)。如何在不更改返回键的情况下更改行时读取新的字符?任何人都有任何想法如何...请分享..
我正在关注此链接Link
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
// Any new character added is passed in as the "text" parameter
if ([text isEqualToString:@"\n"]) {
// Be sure to test for equality using the "isEqualToString" message
[textView resignFirstResponder];
// Return NO so that the final '\n' character doesn't get added
return NO;
}
// For any other character return YES so that the text gets added to the view
return YES;
}
答案 0 :(得分:27)
在iOS 7中,它应该是:
float rows = (textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight;
答案 1 :(得分:26)
您可以查看UITextView的contentSize属性以获取文本的高度(以像素为单位),然后除以UITextView字体的行高间距,以获取总UIScrollView中的文本行数(打开和关闭屏幕) ),包括包装和折线文本。
答案 2 :(得分:4)
extension NSLayoutManager {
var numberOfLines: Int {
guard let textStorage = textStorage else { return 0 }
var count = 0
enumerateLineFragments(forGlyphRange: NSMakeRange(0, numberOfGlyphs)) { _, _, _, _, _ in
count += 1
}
return count
}
}
获取textView中的行数:
let numberOfLines = textView.layoutManager.numberOfLines
答案 3 :(得分:-5)
仅供参考......
另一种获取行数和内容的方法是使用BoltClock在答案编辑中提到的相同方法拆分数组中的行。
NSArray *rows = [textView.text componentsSeparatedByString:@"\n"];
您可以遍历数组以获取每行的内容,并且可以使用[rows count]来获取确切的行数。
要记住的一件事是,空行也将被计算在内。