我从网络服务中获取我的uilabel的内容,所以我想让uilabel变得充满活力。我希望uilabel根据其内容的长度调整宽度。
代码我只减小了文本的大小。
lblWinDesc = [[UILabel alloc] initWithFrame:CGRectMake(winDesString.frame.origin.x, winDesString.frame.origin.y + winDesString.frame.size.height, topLine.frame.size.width, lblOwnerName.frame.size.height)];
lblWinDesc.adjustsFontSizeToFitWidth = YES;
lblWinDesc.numberOfLines =0;
lblWinDesc.layer.borderColor = [UIColor whiteColor].CGColor;
[lblWinDesc setFont:[UIFont boldSystemFontOfSize:20]];
[lblWinDesc setTextColor:[UIColor whiteColor]];
[contentScrollView addSubview:lblWinDesc];
我希望标签在字符/单词达到uilabel的最大宽度时增加其高度
答案 0 :(得分:0)
你可以试试这个......
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
// NSString class method: boundingRectWithSize:options:attributes:context is
// available only on ios7.0 sdk.
CGRect rect = [myString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
//myString is the string you are getting after webservice
现在,您可以使用
动态获取要动态创建的标签的高度rect.size.height;
OR 您可以使用rect作为Label的框架。 [编辑] 检查矩形的高度,制作UILabel并将rect的高度设置为标签
CGFloat heightOfExpectedLabel = rect.size.height;
UILabel myLabel = [UILabel alloc]initWithFrame:CGRectMake(x,y,width,heightOfExpectedLabel);
答案 1 :(得分:0)
lblWinDesc = [[UILabel alloc] initWithFrame:CGRectMake(winDesString.frame.origin.x, winDesString.frame.origin.y + winDesString.frame.size.height, topLine.frame.size.width, lblOwnerName.frame.size.height)];
lblWinDesc.numberOfLines =0;
lblWinDesc.layer.borderColor = [UIColor whiteColor].CGColor;
[lblWinDesc setFont:[UIFont boldSystemFontOfSize:20]];
[lblWinDesc setTextColor:[UIColor whiteColor]];
CGSize maximumLabelSizeValue = CGSizeMake(lblWinDesc.frame.size.width, FLT_MAX);
CGSize expectedSubmittedByValueLabelSize = [_lblWinDesc.text sizeWithFont:_lblWinDesc.font constrainedToSize:maximumLabelSizeValue lineBreakMode:_lblWinDesc.lineBreakMode];
CGRect newSubmittedByValueFrame = _lblWinDesc.frame;
newSubmittedByValueFrame.origin.y=_lblWinDesc.frame.origin.y-2;
newSubmittedByValueFrame.size.height = expectedSubmittedByValueLabelSize.height+5;
[_lblWinDesc setFrame:newSubmittedByValueFrame];
[contentScrollView addSubview:lblWinDesc];
答案 2 :(得分:0)
要动态增加UILable
高度,您还需要计算行数:
CGRect lblRect = self.label.frame;
CGSize maxSize = CGSizeMake(self.label.frame.size.width, MAXFLOAT);
CGRect labelRect = [self.label.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.label.font} context:nil];
CGFloat labelHeight = labelRect.size.height;
int lines = labelHeight / 16; // This is fix height (default height) of your label
[self.label setNumberOfLines:lines];
lblRect.size.height = labelHeight;
[self.label setFrame:lblRect];
答案 3 :(得分:0)
我能够通过将代码放在我设置文本的控制器上来修复它。标签消失,因为还没有文字。
我只是用过:
[myLabel sizeToFit];