LoginSignup
11
9

More than 3 years have passed since last update.

【Swift】UIButtonを画像付きのテキストにする

Last updated at Posted at 2020-06-24

テキストの横に画像のあるボタンを作成したい場面に出会ったことのある人は結構いると思います。
そんな時UIImageUILabelを組み合わせなくてもUIButtonのみで作ることができます。

  • R.swiftを使っています
  • 表示する画像はこちらのイカちゃん

iks.png

完成はこんな感じです。

UIButtonに画像とテキストを設定する

leftImageButton.setTitle("左側アイコン", for: .normal)
leftImageButton.setImage(R.image.ika(), for: .normal)

titleEdgeInsets・imageEdgeInsetsを使います

EdgeInsetsは余白の設定ができます。
それぞれ最適に余白の設定をすることで、ボタンとテキストをいい感じに表示させることができます。
初期値はtitleEdgeInsetsimageEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)なので、画像とテキストを同時に設定すると被って表示されます。

テキストの左に画像を付ける

テキストの左側に余白を設定します。画像のwidthを元に設定するのが良いと思います。

leftImageButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)

テキストの右に画像を付ける

画像を右側に持っていく為に左側にテキストの長さ分の余白を設定します。こちらも固定値を設定していますが、テキストの長さから設定した方が良いと思います。
またテキストの位置も調整したいので、テキストの余白も設定します。

rightImageButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 200, bottom: 0, right: 0)
rightImageButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 20)

仕組みがわかれば同じ要領でテキストの上側に画像を設定したり、下に画像を設定したりできます。

テキストの上に画像を付ける

topImageButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 100, bottom: 20, right: 0)
topImageButton.titleEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

テキストの下に画像を付ける

bottomImageButton.imageEdgeInsets = UIEdgeInsets(top: 25, left: 100, bottom: 0, right: 0)
bottomImageButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)

以上です。
仕組みを理解すれば簡単にちょっと凝ったボタンを作成することができてとても便利です。

関連

【Swift】UIButtonにimageをセットしたが表示されない件

11
9
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
11
9