码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-11 12:04:32      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:ios开发   textview   

由于项目中要用到在一个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;
}


UITextView根据内容、字体属性自动调节自己的大小,布布扣,bubuko.com

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

标签:ios开发   textview   

原文地址:http://blog.csdn.net/feixiang_song/article/details/38488557

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!