如果您可以通過界面構建器添加標籤,它將節省大量的標籤屬性代碼,儘管從您所描述的內容來看,如果您使用下面的代碼(替換所需的位置,大小和文本值),那麼這個標籤會根據你填充的內容而改變。我一直使用它,完美地工作。
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.
我希望這可以幫助你找到你要找的東西。
(這取代了需要任何約束的編碼,你有太多。)
乾杯,吉姆
,如果你希望它有多行,你必須做出'numberOfLines'大於0 – user2277872
我已將其設置爲零,因爲我沒有多少準確的數據,並且我在某處將其設置爲零將會處理它 – Haagenti
http://stackoverflow.com/questions/18315441/with-what-should -i-replace-the-deprecated-sizewithfontcontrainedtosizelinebrea ?? –