LoginSignup
6
4

More than 5 years have passed since last update.

UIButtonのAutolayoutがtitleEdgeInsetsを考慮していないので対応した

Posted at

便利にしたい点

InterfaceBuilder上のUIButtonにtitleEdgeInsetsを設定し、
ボタンの文言のみをプログラム上で設定(変更)すると文言の長さによって
ボタンのサイズが変更されるが、そのサイズにtitleEdgeInsetsが反映されていないため
表示が崩れてしまう。

名称未設定.png
収まってくんない

タイトルを変更した事をAutolayoutに明示的に通知する必要があるのかと思い、
以下のコードを実行してみました。

botton.setTitle("収めて収めて収めて収めて収めて", forState: .Normal)
// AutolayoutにintrinsicContentSizeが変更された事を伝える
button.invalidateIntrinsicContentSize()

名称未設定.png
収まってくんない

対応

調べてみた結果、intrinsicContentSizeがそもそもtitleEdgeInsetsを考慮していないということが判明したので以下のようなUIButtonのextensionを実装

extension UIButton {
    public override func intrinsicContentSize() -> CGSize {
        let originalContentSize = super.intrinsicContentSize()
        let adjustedWidth = originalContentSize.width + titleEdgeInsets.left + titleEdgeInsets.right
        let adjustedHeight = originalContentSize.width + titleEdgeInsets.top + titleEdgeInsets.bottom
        return CGSize(width: adjustedWidth, height: adjustedHeight)
    }
}

返り値のCGSizeに対してそれぞれ、edgeInsetsの値を足してあげる。
すると・・・・・

収めて.png
収まってくれた

感想

ちょっとした気の利かない部分にイラッとしちゃいました:man_with_gua_pi_mao:
UIButtonにはこれとは別にimageEdgeInsetsも存在しているので、imageEdgeInsetsでイラッとした方は同じ手順で改善されるかと思います。

6
4
1

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
6
4