0
已經有很多與此主題相關的線程,但我從來沒有找到正確的方式來獲取iOS7和iOS8中的UITextView的行數。下面是我認爲最好的一種,但是當文字字體很小時仍然有一些問題。任何人都有更好的解決方案?在iOS7和iOS8中獲取UITextView的行數的正確方法
第1步:在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以上