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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值