天天看点

iOS UILabel计算高度与宽带

1、在IOS开发中,我们经常需要根据文本的长短动态的设置UILabel的显示位置,这时我们就需要知道UILabel的宽与高。

在IOS6.0以及以前的版本计算UILabel的高度与宽度,在IOS7.0 sizeWithFont被遗弃不在使用。

        1、1 定义单行字符串,计算Label的宽度与高度

NSString *[email protected]"欢迎访问";
    	UILabel *label=[[UILabel alloc] init];
    	[label setNumberOfLines:1];
    	CGSize size=CGSizeMake(320, 20);
    	label.text=content;
    	UIFont *font=[UIFont fontWithName:@"Arial" size:12.0f];
    	label.font=font;
    	CGSize labelsize=[content sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByTruncatingTail];
    	label.frame=CGRectMake(10, 10, labelsize.width, labelsize.height);
    	[self.view addSubview:label];
    	[label release];
           

       1、2 定义多行字符串

NSString *[email protected]"欢迎访问天猫购物商城,祝您购物愉快";
    UILabel *label=[[UILabel alloc] init];
    [label setNumberOfLines:0];//设置行数为零,即不做限制
    CGSize size=CGSizeMake(320, 1000);
    label.text=content;
    UIFont *font=[UIFont fontWithName:@"Arial" size:12.0f];
    label.font=font;
    //NSLineBreakByWordWrapping以单词为单位换行
    CGSize labelsize=[content sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    label.frame=CGRectMake(10, 10, labelsize.width, labelsize.height);
    [self.view addSubview:label];
    [label release];
           

2    在IOS7.0获取UILabe的宽度与高度

NSString *[email protected]"欢迎访问天猫购物商城,祝您购物愉快";
    	UILabel *label=[[UILabel alloc] init];
    	[label setNumberOfLines:0];//设置行数为零,即不做限制
    	CGSize size=CGSizeMake(320, 1000);
    	label.text=content;
    	UIFont *font=[UIFont fontWithName:@"Arial" size:12.0f];
    	label.font=font;
   
    	NSMutableParagraphStyle *paragraph=[[[NSMutableParagraphStyle alloc] init] autorelease];
    	paragraph.lineBreakMode=NSLineBreakByWordWrapping;
    	paragraph.alignment=NSTextAlignmentCenter;
    
     	NSAttributedString *attributeText=[[[NSAttributedString alloc] initWithString:content attributes:@{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraph}] autorelease];
    	//options 有多个参数,详见苹果官方解释
    	CGSize labelsize=[attributeText boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
        labelsize=CGSizeMake(ceilf(labelsize.width),ceilf(labelsize.height));
    
    	label.frame=CGRectMake(10, 10, labelsize.width, labelsize.height);
    	[self.view addSubview:label];
    	[label release];