1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

UILabelの幅と高さを自動で設定する

Last updated at Posted at 2021-01-06

はじめに

SnapKitを使いコードベースでレイアウトを組むようになってからテキストを持つUI部品の幅や高さを意識するようになりました。ここではwidthやheightを自動で設定する方法について記録を残します。

悩み

Simulator Screen Shot - iPhone 12 - 2021-01-06 at 17.53.19.png
コードベースでレイアウトを組むようにしたものの、widthheightの設定が上手くいかない!というかメンドくさい!

private func setupLabel() {
        label.text = "あいうえお"
        label.backgroundColor = .red
        view.addSubview(label)
        label.snp.makeConstraints {
            $0.width.equalTo(60)//ここを定数にしてしまっているため、いい感じになるまで何度も確認しなければならない
            $0.height.equalTo(30)//同様
            $0.center.equalToSuperview()
        }
    }
}

解決方法

sizeThatFitsgreatestFiniteMagnitudeを使います。

private func setupLabel() {
        label.text = "あいうえお"
        label.backgroundColor = .red
        let size = label.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
        view.addSubview(label)
        label.snp.makeConstraints {
            $0.width.equalTo(size.width)
            $0.height.equalTo(size.height)
            $0.center.equalToSuperview()
        }
    }

Simulator Screen Shot - iPhone 12 - 2021-01-06 at 17.57.47.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?