2014-02-18 65 views
0

我想在我的视图的顶部添加一个UILabel,它可以是多行。我已经研究过,但是我无法实现,因为它只会显示一行,而且我希望它能够像所需的那样大。我与自动布局和当前代码我这样做是这样的:iOS UILabel高度

UILabel *label = [[UILabel alloc] init]; 
label.translatesAutoresizingMaskIntoConstraints = NO; 
label.text = @"jklljk sdkhfdjkdsfjhkfk fhs fdh fk dksdks dfss s dfs dfs fsdkdfks dfks dfks df k dfh"; 
label.numberOfLines = 0; 

NSDictionary *views = @{@"label" : label}; 
[self.view addSubview:label]; 
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[label]|" options:0 metrics:nil views:views]]; 
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label(>=20)]" options:0 metrics:nil views:views]]; 
+0

,如果你希望它有多行,你必须做出'numberOfLines'大于0 – user2277872

+2

我已将其设置为零,因为我没有多少准确的数据,并且我在某处将其设置为零将会处理它 – Haagenti

+0

http://stackoverflow.com/questions/18315441/with-what-should -i-replace-the-deprecated-sizewithfontcontrainedtosizelinebrea ?? –

回答

0

你需要设置一个帧标签来设置它在视图初始位置。

从视图编程指南:

当添加一个子视图到其父,子视图的当前帧的矩形表示其父视图内的初始位置。

+0

使用VFL时,您不适用于框架 – Haagenti

0

尝试调用:

[self.view layoutIfNeeded]; 

后添加的约束。这应该用新的限制来更新视图。

0

如果您可以通过界面构建​​器添加标签,它将节省大量的标签属性代码,尽管从您所描述的内容来看,如果您使用下面的代码(替换所需的位置,大小和文本值),那么这个标签会根据你填充的内容而改变。我一直使用它,完美地工作。

UILabel *label = [[UILabel alloc] initWithFrame:GCRectMake(0,0,300, 50)]; //these values to be changed to reflect where you want the label to appear, initial position and size, width etc. 
//setting up the label attributes etc 
label.numberOfLines = 0; //This means there's no limit to lines of text. 
label.font = [UIFont systemFontOfSize:13]; 
label.textColor = [UIColor blackColor]; 

NSString *content = YOUR_TEXT;// your example @"jklljk sdkhfdjkdsfjhkfk fhs fdh fk dksdks dfss s dfs dfs fsdkdfks dfks dfks df k dfh"; 

CGSize maximumLabelSize = CGSizeMake(300, 1000); //For example - the height can be changed to any maximum value. 

NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName]; //This allows a calculation to be made of the space taken up, so if you're using a custom or large font it will calculate accordingly. 

CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size; 

CGRect frame = label.frame; 
frame.size.height = newExpectedLabelSize.height; 
label.frame = frame; //This last line should change the height of your label according to what it needs to be to have all the text visible and over multiple lines. 

我希望这可以帮助你找到你要找的东西。

(这取代了需要任何约束的编码,你有太多。)

干杯,吉姆