//高度自适应 UIFont *font = [UIFont fontWithName:@"Arial" size:13]; //设置一个行高上限 CGSize size = CGSizeMake(320,1000); //计算实际frame大小,并将label的frame变成实际大小 CGSize labelsize = [entity.content sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; DebugLog(@"height = %f", height) ;
方法一: CGSize titleSize = [titleContent boundingRectWithSize:CGSizeMake(kScreen_Width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size; 或方法二: CGSize labelsize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; //获取单行字符串的宽度和高度 NSString *content = @"获取 UILabel 宽度和高度测试"; CGSize size =[content sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]}]; //获取多行字符串的宽度和高度 UILabel *titleLabel = [[UILabel alloc]init]; titleLabel.font = [UIFont systemFontOfSize:1]; NSString *titleContent = @"获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试"; titleLabel.text = titleContent; titleLabel.numberOfLines = 0;//多行显示,计算高度 titleLabel.textColor = [UIColor lightGrayColor]; CGSize titleSize = [titleContent boundingRectWithSize:CGSizeMake(kScreen_Width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size; titleLabel.size = titleSize; titleLabel.x = 0; titleLabel.y = 0; [self.view addSubview:titleLabel]; //或者 //初始化label UILabel *label = [[UILabel alloc] init]; //设置自动行数与字符换行 [label setNumberOfLines:0]; [label.lineBreakMode:UILineBreakModeWordWrap]; // 测试字串 NSString *str = @"获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试获取 UILabel 宽度和高度测试"; UIFont *font = [UIFont fontWithName:@"Arial" size:13]; //设置一个行高上限 CGSize size = CGSizeMake(320,1000); //计算实际frame大小,并将label的frame变成实际大小 CGSize labelsize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap]; [label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];
时间: 2024-10-05 07:21:13