自定义label高度

来源:互联网 发布:浪潮软件免费下载 编辑:程序博客网 时间:2024/06/01 21:21

创建一个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的高度//  结构体赋值 (不能直接赋值 要用中间变量转化)(直接赋值会导致系统把 点语法 与 frame (结构体) 的点 混用)CGRect temp = label.frame;temp.size.height = frame.size.height ;label.frame = temp;




0 0
原创粉丝点击