【发布时间】:2015-07-10 21:48:06
【问题描述】:
已经有很多与这个主题相关的线程,但我一直找不到正确的方法来获取 iOS7 和 iOS8 中 UITextView 的行号。以下是我认为最好的方式,但是当文本字体很小时仍然存在一些问题。谁有更好的解决方案?
Step1:获取UITextView中的文字高度。来自:Resize font size to fill UITextView?
- (float) getTextSizeHeight:(UITextView *) textView{
[iConsole info:@"%s",__FUNCTION__];
CGSize tallerSize = CGSizeMake(textView.frame.size.width-16,999);
CGSize stringSize;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:NSLineBreakByWordWrapping];
} else {
stringSize = [textView.text sizeWithFont:textView.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
}
CGFloat textHeight = stringSize.height; //textView.contentSize.height is not the right way
return textHeight;
}
Step2:计算行号
- (int) lineNumberWithUITextView:(UITextView *) textView
{
float textHeight = [self getTextSizeHeight:textView];
float lineHeight = textView.font.lineHeight;
float numLines = textHeight / lineHeight;
int returnVal = ceilf(numLines);
return returnVal;
}
【问题讨论】:
标签: ios uitextview