控件类

自动计算Label高度、宽度

2016-10-21  本文已影响82人  Liberalism

自动计算高度和宽度的关键点无外乎三个因素,文字内容,宽度或高度,再者就是字号,通过这三个因素,去自动计算对应的高度或宽度

自动计算高度




-(CGRect)contentRectWithString:(NSString *)string labelWidth:(CGFloat)labelWidth AndStringFont:(int)fontSize
{
    CGRect tempRect = [string boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
    
    return tempRect;
}


自动计算宽度


-(CGRect)contentRectWithString:(NSString *)string labelHeight:(CGFloat)labelHeight AndStringFont:(int)fontSize
{
    CGRect tempRect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, labelHeight)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
    
    return tempRect;
}

示例代码

#import "ViewController.h"
#import "Masonry.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *myLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.myLabel = (UILabel *)[self.view viewWithTag:3];
    
    [self.view addSubview:self.myLabel];
    
    self.myLabel.numberOfLines = 0;
    
    NSString *str = @"豫章故郡,洪都新府。星分翼轸,地接衡庐。襟三江而带五湖,控蛮荆而引瓯越。物华天宝,龙光射牛斗之墟;人杰地灵,徐孺下陈蕃之榻。雄州雾列,俊采星驰。台隍枕夷夏之交,宾主尽东南之美。都督阎公之雅望,棨戟遥临;宇文新州之懿范,襜帷暂驻。十旬休假,胜友如云;千里逢迎,高朋满座。腾蛟起凤,孟学士之词宗;紫电青霜,王将军之武库。家君作宰,路出名区;童子何知,躬逢胜饯。时维九月,序属三秋。潦水尽而寒潭清,烟光凝而暮山紫。俨骖騑于上路,访风景于崇阿。临帝子之长洲,得仙人之旧馆。层峦耸翠,上出重霄;飞阁流丹,下临无地。鹤汀凫渚,穷岛屿之萦回;桂殿兰宫,列冈峦之体势。披绣闼,俯雕甍,山原旷其盈视,川泽纡其骇瞩。闾阎扑地,钟鸣鼎食之家;舸舰迷津,青雀黄龙之舳。云销雨霁,";
    
    
    CGRect labelRect = [self contentRectWithString:str labelWidth:200.0 AndStringFont:15.0];

    float height = labelRect.size.height;

    [self.myLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(height);
        
    }];
    
    self.myLabel.text = str;
    

}

-(CGRect)contentRectWithString:(NSString *)string labelWidth:(CGFloat)labelWidth AndStringFont:(int)fontSize
{
    CGRect tempRect = [string boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil];
    
    return tempRect;
}

上一篇 下一篇

猜你喜欢

热点阅读