LoginSignup
0
1

More than 5 years have passed since last update.

UIButtonのImageとLabelを縦積み配置にする

Posted at

はじめに

UIButtonはImageとLabelに関してデフォルトでは以下のような配置を行います

Image Label

Imageが左に、Labelが右に、という感じです。しかし、時々以下のような配置をしたくなるときがあります。

Image
Label

Imageの下にLabelを配置しています。AndroidのButtonであれば、drawableTopを使ってやることで簡単にこのような見た目を実現できるのですが、iOSではそうもいきません。少し工夫が必要だったので方法を共有します。

やり方

UIEdgeInsetsを使用してLabelとImageをそれぞれのサイズ分ずらしてやります

if let titleLabel = button.titleLabel, let titleImage = button.imageView {
    button.titleEdgeInsets = UIEdgeInsets(top: 0,
                                          left: -titleImage.bounds.size.width,
                                          bottom: -titleImage.bounds.size.height,
                                          right: 0)
    button.imageEdgeInsets = UIEdgeInsets(top: -titleLabel.bounds.size.height,
                                          left: 0,
                                          bottom: 0,
                                          right: -titleLabel.bounds.size.width)
}

UIEdgeInsetsにわたすパラメータを調整することで、ImageとLabel間のマージンを設定してやることも出来ます。

0
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
0
1