如何根据String调整UILabel宽度
我有一个UITableView
,充满了自定义单元格。 自定义单元格有许多标签。 一个标签,它从db中获取不同大小的字符串。 我想要的是下一个标签在第一个标签之后(在第一个标签的字符串的末尾)开始。 我用过这段代码:
cell.Manufactlbl.adjustsFontSizeToFitWidth=YES; CGSize lLabelSIze = [coffeeObj.price sizeWithFont: cell.Manufactlbl.fontforWidth:cell.Manufactlbl.frame.size.width lineBreakMode:cell.Manufactlbl.lineBreakMode]; cell.Manufactlbl.frame = CGRectMake(cell.Manufactlbl.frame.origin.x, cell.Manufactlbl.frame.origin.y, cell.Manufactlbl.frame.size.width, lLabelSIze.height); cell.Manufactlbl.font=[UIFont systemFontOfSize:12]; cell.Manufactlbl.text=coffeeObj.price; cell.Typelbl.frame=CGRectMake(cell.Manufactlbl.frame.origin.x + cell.Manufactlbl.frame.size.width, cell.Typelbl.frame.origin.y, cell.Typelbl.frame.size.width, cell.Typelbl.frame.size.height); cell.Typelbl.font=[UIFont systemFontOfSize:12]; cell.Typelbl.text=coffeeObj.instrument;`
但这不起作用。
尝试这个。
CGSize size = [@"Your string" sizeWithFont:[UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:22] constrainedToSize:CGSizeMake(500, CGFLOAT_MAX)]; _Lable.frame = CGRectMake(05,05, 50, size.height);
希望它对你有所帮助..
您可以执行以下操作:调整每个标签的大小(使标签对文本足够大),然后将每个标签的框架设置为依赖于其他标签。 例如:
[labelOne sizeToFit]; [labelTwo sizeToFit]; labelTwo.frame = CGRectMake(CGRectGetMaxX(labelOne.frame), labelTwo.origin.y, labelTwo.frame.size.width, labelTwo.frame.size.height);
谷歌NS(归因)字符串+几何学它解决了它
试试这段代码:
NSString *text1 = @"example text1 "; CGSize maximumLabelSize = CGSizeMake(236,9999); CGSize expectedLabelSize = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeCharacterWrap]; UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(50 ,0, expectedLabelSize.width, expectedLabelSize.height)]; label1.font = [UIFont systemFontOfSize:12]; label1.text = text1; NSString *text2 = @"example Text2"; expectedLabelSize = [text2 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeCharacterWrap]; UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x + label1.frame.size.width ,0, expectedLabelSize.width, expectedLabelSize.height)]; label2.font = [UIFont systemFontOfSize:12]; label2.text = text2; [self.view addSubview:label1]; [self.view addSubview:label2];