當 Label 的文字長度不固定時,我們往往需要根據內容自動計算它應該佔據的高度。本文示範如何用 sizeWithFont:constrainedToSize:lineBreakMode: 來達成。
UILabel * label = [[UILabel alloc] init]; NSString * text = @"hellohellohellohellohellohellohellohellohellohellohellohello "; label.text = text; [label setNumberOfLines:0]; //允許自動換行 UIFont *font = [UIFont fontWithName:@"Arial" size:14]; //設定字型 label.font = font; CGSize size = CGSizeMake(300, 20000.0f); size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping]; [label setFrame:CGRectMake(10, 0, size.width, size.height)]; [self.view addSubview:label];
lineBreakMode 用來設定文字過長時的顯示方式:
上述程式碼可正常運行。但還會遇到一個問題:如果這個 label 是動態生成的沒問題,可若是從 storyboard 拖出來、並在 controller 中連上對應屬性的 label,那麼對它呼叫 setFrame 往往無效。
這時可以點開右側的 Size Inspector,在 Constraints 中找到 height equals 這一項,點擊後面的齒輪圖案選擇 Select and Edit,把 height constraint 的 Priority 數值調小一些即可。這樣程式碼設定的 frame 才不會被自動布局的約束給覆蓋。