LoginSignup
9
7

More than 5 years have passed since last update.

【iOS】可変サイズに対応して余白を設定するLabelを作る

Last updated at Posted at 2017-09-02

background colorのあるlabelを作成する際に、背景に対して文字の余白が無い状態で表示されます。

nomallabel.png

こういった場合は、UIButtonのInsetsの設定を利用すると簡単に余白を出すことができます。

まずstoryboardで、Insetsの変更します。
text部分の余白を作るのでTitle Insetsを変更します。

insets1.png

画像では、左側と右側に5ポイント余白を作りました。
しかし、これだけでは、文字が...となって全て表示されなくなります。

labelinsets.png

そこで、Content自体のInsetsを変更します。

insets2.png

Title Insetsの右側も-5に変更します。
すると、無事に背景に対して余白ができました。

buttonInsets.png

上のLabelと比べても余白ができているのがわかります。
あとは、ButtonのEnabledを変更してボタン機能を無くせばラベルと同じうようになります。

簡単な背景色のあるLabelを作る場合は、この方が楽に作れると思います。

コードで書く場合

button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10)
button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, -5)
9
7
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
9
7