Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

はじめに

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間のマージンを設定してやることも出来ます。

retty
Retty株式会社はソーシャルメディア、スマートフォンを活かした「人を軸にお店を探せる」グルメサービスRettyを運営する会社です。
https://retty.me
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした