設定 UILabel 高度時,不能只用 font size,否則文字可能被裁切。可依場景選擇 sizeThatFits、sizeToFit、sizeWithAttributes 或 boundingRectWithSize。
兩者都會回傳適合顯示的尺寸。差別是 sizeToFit 會改變 view 的 bounds,sizeThatFits 不會。
CGSize size = [testLabel sizeThatFits:CGSizeMake(200, 30)];
sizeWithAttributes 與 boundingRectWithSize 可直接用字串與字型計算。boundingRectWithSize 支援多行與 options,例如 NSStringDrawingUsesLineFragmentOrigin。
不同 API 回傳值可能略有差異,且字級越大,預留空間越明顯。若需要精準排版,建議實測並保留些許高度餘裕。