2014-10-27 58 views
1

我正在編寫一個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是最大寬度?這很重要,因爲我稍後在某些約束中使用這些值,並且重要的是此最大寬度保持不變。

謝謝。

+0

也許double =當你想要初始化contentWidth導致問題? – Imotep 2014-10-27 20:22:55

+0

感謝您指出這一點,但不幸的是,這是在編輯我正在編寫的問題時發生的錯誤。檢查我的代碼,這是沒問題的。 – Greeso 2014-10-27 20:27:38

回答

1

Apple's reference,有一個有趣的討論:

這個方法返回字符串中的字形的實際邊界。 允許某些字形(例如空格)與傳入的大小指定的佈局約束重疊,因此在某些情況下,返回的CGRect的大小分量的寬度值可以是 超過寬度值大小參數。

這應該是你在找什麼。結果寬度是否比您提供的「最大值」大很多?如果沒有,我猜這個討論會回答你。

+0

它不是很大,也許是幾個像素或三個。但是這會影響整個佈局。如果這只是由於空白,那麼我不認爲這會造成問題,因爲我將設置固定的最大寬度,因此截斷的空白不會導致問題。 – Greeso 2014-10-27 20:52:07