UILabelやNSTextFieldなどのコンポーネントの高さを指定して,中のテキストのフォントサイズを自動で調節しようと思い,フォントサイズを変化させた時のUILabelとNSTextFieldの大きさを見てみました.
Playgroundでシミュレートして大きさを表示させてみた
UILabel
UIKit.playground
import UIKit
let label = UILabel(frame: CGRect.zero)
label.text = "あいうえお"
for i in (1...50) {
label.font = UIFont.systemFont(ofSize: CGFloat(i))
label.sizeToFit()
print("\(i), \(label.frame.height)")
}
NSTextField
Cocoa.playground
import Cocoa
let label = NSTextField(labelWithString: "あいうえお")
for i in (1...50) {
label.font = NSFont.systemFont(ofSize: CGFloat(i))
label.sizeToFit()
print("\(i), \(label.frame.height)")
}
結果
フォントサイズ1~50までの結果をプロットしてみました.
| フォントサイズ | UILabelのheight | NSTextFieldのheight |
|---|---|---|
| 1 | 1.5 | 2.0 |
| 2 | 2.5 | 3.0 |
| 3 | 4.0 | 5.0 |
| 4 | 5.0 | 6.0 |
| 5 | 6.0 | 7.0 |
| 6 | 7.5 | 8.0 |
| 7 | 8.5 | 9.0 |
| 8 | 10.0 | 11.0 |
| 9 | 11.0 | 11.0 |
| 10 | 12.0 | 13.0 |
| 11 | 13.5 | 14.0 |
| 12 | 14.5 | 16.0 |
| 13 | 16.0 | 17.0 |
| 14 | 17.0 | 18.0 |
| 15 | 18.0 | 19.0 |
| 16 | 19.5 | 19.0 |
| 17 | 20.5 | 21.0 |
| 18 | 21.5 | 22.0 |
| 19 | 23.0 | 23.0 |
| 20 | 24.0 | 24.0 |
| 21 | 25.5 | 25.0 |
| 22 | 26.5 | 27.0 |
| 23 | 27.5 | 28.0 |
| 24 | 29.0 | 29.0 |
| 25 | 30.0 | 30.0 |
| 26 | 31.5 | 31.0 |
| 27 | 32.5 | 33.0 |
| 28 | 33.5 | 34.0 |
| 29 | 35.0 | 35.0 |
| 30 | 36.0 | 36.0 |
| 31 | 37.0 | 38.0 |
| 32 | 38.5 | 39.0 |
| 33 | 39.5 | 40.0 |
| 34 | 41.0 | 41.0 |
| 35 | 42.0 | 42.0 |
| 36 | 43.0 | 44.0 |
| 37 | 44.5 | 45.0 |
| 38 | 45.5 | 46.0 |
| 39 | 47.0 | 47.0 |
| 40 | 48.0 | 48.0 |
| 41 | 49.0 | 50.0 |
| 42 | 50.5 | 51.0 |
| 43 | 51.5 | 52.0 |
| 44 | 53.0 | 53.0 |
| 45 | 54.0 | 54.0 |
| 46 | 55.0 | 55.0 |
| 47 | 56.5 | 56.0 |
| 48 | 57.5 | 57.0 |
| 49 | 58.5 | 58.0 |
| 50 | 60.0 | 60.0 |
コンポーネントの高さに合わせたフォントサイズの指定
トレンドラインの数式を元に今の高さにあったフォントサイズを出力します.
UILabel
func adjustUILabelFontSize() {
let h = label.frame.height
let fontSize: CGFloat = (2.0 * (h - 0.249) / 1.1934).rounded() / 2.0
label.font = UIFont.systemFont(ofSize: fontSize)
label.sizeToFit()
}
NSTextField
func adjustNSTextFieldFontSize() {
let h = label.frame.height
let fontSize: CGFloat = (2.0 * (h - 1.0278) / 1.177).rounded() / 2.0
label.font = NSFont.systemFont(ofSize: fontSize)
label.sizeToFit()
}
備考
UILabelの場合は.adjustsFontSizeToFitWidthという幅にあった大きさのフォントに調節するやつがあります.
