我正在編寫一個iPhone應用程序,在該應用程序中,我在運行時創建了一個帶有動態內容的UILabel。我無法控制UILabel的內容,因此我必須計算其大小,以便稍後可以使用這些大小值來設置一些UI約束。boundingRectWithSize:options:attributes:context:未返回準確的預期UILabel大小
我使用以下代碼來創建的UILabel並計算其預期大小:
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.font = [UIFont fontWithName:@"Arial-Bold" size:20];
titleLabel.numberOfLines = 0;
titleLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vulputate venenatis justo in ultrices. Pellentesque eu pharetra elit, id faucibus mi.";
//Calculate the expected lable size
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
CGFloat contentWidth = applicationFrame.size.width - 20; // 20 is 10+10, a margin of 10 from each side
CGSize maximumLabelSize = CGSizeMake(contentWidth, FLT_MAX); // FLT_MAX here simply means max possible height
CGRect expectedLabelSize = [titleLabel.text boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{
NSFontAttributeName:titleLabel.font
}
context:nil];
當我運行上面的代碼中,值expectedLabelSize.size.width
有時比傳遞到boundingRectWithSize:options:attributes:context:
原始contentWidth
值大。我如何確保contentWidth
是最大寬度?這很重要,因爲我稍後在某些約束中使用這些值,並且重要的是此最大寬度保持不變。
謝謝。
也許double =當你想要初始化contentWidth導致問題? – Imotep 2014-10-27 20:22:55
感謝您指出這一點,但不幸的是,這是在編輯我正在編寫的問題時發生的錯誤。檢查我的代碼,這是沒問題的。 – Greeso 2014-10-27 20:27:38