在 iOS7 和 iOS8 中获取 UITextView 行号的正确方法
Correct way to get line number of UITextView in iOS7 and iOS8
已经有很多与此主题相关的线程,但我一直无法在 iOS7 和 iOS8 中找到获取 UITextView 行号的正确方法。下面是我认为最好的方法,但是当文本字体较小时仍然存在一些问题。有人有更好的解决方案吗?
第一步:获取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;
}
第二步:计算行号
- (int) lineNumberWithUITextView:(UITextView *) textView
{
float textHeight = [self getTextSizeHeight:textView];
float lineHeight = textView.font.lineHeight;
float numLines = textHeight / lineHeight;
int returnVal = ceilf(numLines);
return returnVal;
}
在上面的ios7中,您可以使用:
float rows = round((textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight);
已经有很多与此主题相关的线程,但我一直无法在 iOS7 和 iOS8 中找到获取 UITextView 行号的正确方法。下面是我认为最好的方法,但是当文本字体较小时仍然存在一些问题。有人有更好的解决方案吗?
第一步:获取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;
}
第二步:计算行号
- (int) lineNumberWithUITextView:(UITextView *) textView
{
float textHeight = [self getTextSizeHeight:textView];
float lineHeight = textView.font.lineHeight;
float numLines = textHeight / lineHeight;
int returnVal = ceilf(numLines);
return returnVal;
}
在上面的ios7中,您可以使用:
float rows = round((textView.contentSize.height - textView.textContainerInset.top - textView.textContainerInset.bottom) / textView.font.lineHeight);