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

根据文字动态调整 UILabel 高度

时间:2014-12-02 19:15:19      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:uilabel   ios   动态调整高度   

#import <UIKit/UIKit.h>

@interface UILabel (dynamicSize)
-(float)resizeToFit;
-(float)expectedHeight;
@end


#import "UILabel+dynamicSize.h"

@implementation UILabel (dynamicSize)
-(float)resizeToFit{
    float height = [self expectedHeight];
    CGRect newFrame = [self frame];
    newFrame.size.height = height;
    [self setFrame:newFrame];
    return newFrame.origin.y + newFrame.size.height;
}

-(float)expectedHeight{
    [self setNumberOfLines:0];
    [self setLineBreakMode:NSLineBreakByCharWrapping];
    
    UIFont *font = [UIFont systemFontOfSize:14.0];
    
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          font, NSFontAttributeName,
                                          nil];
    
    CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,9999);
    
    CGRect expectedLabelRect = [[self text] boundingRectWithSize:maximumLabelSize
                                                         options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                                      attributes:attributesDictionary
                                                         context:nil];
    CGSize *expectedLabelSize = &expectedLabelRect.size;
    
    return expectedLabelSize->height + self.frame.size.height;
}
@end

测试一下OK,通过。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 150, 35)];
    label.backgroundColor = [UIColor lightGrayColor];
    label.text = @"This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.hahhaha";
    CGRect newRect = label.frame;
    newRect.size.height = [label expectedHeight];
    label.frame = newRect;
    [self.view addSubview:label];
}

参考:

UILabel - auto-size label to fit text?


根据文字动态调整 UILabel 高度

标签:uilabel   ios   动态调整高度   

原文地址:http://blog.csdn.net/chaoyuan899/article/details/41682013

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