[TwistedFate]Label自适应高度

来源:互联网 发布:经典日剧知乎 编辑:程序博客网 时间:2024/05/16 19:24

Label的自适应高度

创建一个label

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 300, 100)];label.numberOfLines = 0;label.font = [UIFont systemFontOfSize:16];label.backgroundColor = [UIColor grayColor];NSString *str = @" --  --- - -- -- -- -- -- -- ---....... ";label.text = str;[self.window addSubview:label];[label release];

自适应高度思路

计算字符串的所占高度
定值:宽度 字体大小
参数size : 宽度 与 label的宽度一样

构建字体大小的字典

 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil];

求出自适应高度

//  CGFLOAT_MAX最大浮点数 CGRect frame = [str boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];NSLog(@"%f",frame.size.height);//  更改label的高度//  结构体赋值CGRect temp = label.frame;temp.size.height = frame.size.height ;label.frame = temp;
2 0
原创粉丝点击