2014-02-18 66 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. 

我希望這可以幫助你找到你要找的東西。

(這取代了需要任何約束的編碼,你有太多。)

乾杯,吉姆