简介
UILabel主要用于文字等信息的展示,没有UIButton类似的Send Event。
我们既可以在IB中添加UILabel,也可以在代码中动态创建UILabel,
IB中创建可以参考UIButton使用,
动态创建,看一下下面简单的代码
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 80, 250, 40)];
[label setFont:[UIFont systemFontOfSize:40]];
[label setText:@"尚无评价信息"];
[self.view addSubview:label];
使用特例
我们用UILabel,来显示信息时,会遇到根据内容来设置UILabel的高度,下面是实现代码
// UILable的宽度
CGFloat contentWidth = 259.000;
// 根据字体计算高度
UIFont *baseFone = [UIFont systemFontOfSize:13];
// 获取UILabel将要显示的数据
NSString *content = [data objectForKey:@"content"];
// 1000仅仅是个约数,只要保证content能显示完整就行
// 在IB中要把UILabel的换行类型设置为UILineBreakModeWordWrap
CGSize contentSize = [content sizeWithFont:baseFone constrainedToSize:CGSizeMake(contentWidth, 10000) lineBreakMode:UILineBreakModeWordWrap];
// IB中一定要将UILabel的Layout属性的Lines设置为0,以保证宽度自适应
CGRect frame = [cell.contentLabel textRectForBounds:cell.contentLabel.frame limitedToNumberOfLines:0];
frame.size.height = size.height;
// 通过frame.origin.x 和 frame.origin.y来定位元素
frame.origin.y = otherHeight + cell.otherLabel.frame.size.height;
cell.contentLabel.frame = frame;
根据内容来计算内容的高度,然后再把确定UIlabel的高度。