首页 > 代码库 > UITextView根据内容、字体属性自动调节自己的大小

UITextView根据内容、字体属性自动调节自己的大小

由于项目中要用到在一个scrollview中添加多个标题view、textview,所以他们的布局就尤为重要了,我们必须只有严格知道各个视图的大小才能编辑每个视图的frame,才能添加到scrollview中。那么当我们的textview的text特别多,非常多时,自动计算自己的高度就比较重要了

下面是我的工程用到的方法,再此记录,

/**
 *  This method is used to calculate height of text given which fits in specific width having    font provided
 *
 *  @param text       Text to calculate height of
 *  @param widthValue Width of container
 *  @param font       Font size of text
 *
 *  @return Height required to fit given text in container
 */

- (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
    CGFloat result = font.pointSize+4;
    CGFloat width = widthValue;
    if (text) {
        CGSize textSize = { width, CGFLOAT_MAX };       //Width and height of text area
        CGSize size;
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
            //iOS 7
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
            paragraphStyle.lineHeightMultiple = 20.f;
            paragraphStyle.maximumLineHeight = 25.f;
            paragraphStyle.minimumLineHeight = 15.f;
            paragraphStyle.firstLineHeadIndent = 20.f;
            paragraphStyle.alignment = NSTextAlignmentJustified;
            
            NSDictionary *attributes = @{ NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle, NSForegroundColorAttributeName:[UIColor colorWithRed:76./255. green:75./255. blue:71./255. alpha:1]
                                          };
            CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];
            size = CGSizeMake(frame.size.width, frame.size.height+1);
        }
        else
        {
            //iOS 6.0
            size = [text sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
        }
        result = MAX(size.height, result); //At least one row
    }
    return result;
}