LoginSignup
15
16

More than 5 years have passed since last update.

UILabelを角丸 or パディングしたいならUIButtonで代用するテク

Last updated at Posted at 2015-02-04

UILabelで角丸が付いたものや、パディングしたいと思っても若干面倒そう。

UILabelを角丸にする&パディングを設定する方法

代わりにUIButtonが使えるよね。っていう話です。
image

var buttonAsLabel = UIButton(frame: CGRectMake(100, 100, 200, 50))

//テキスト入れる
buttonAsLabel.setTitle("ラベルの代わりに", forState: .Normal)
//角丸を指定できる
buttonAsLabel.layer.cornerRadius = 15
//テキストのカラー
buttonAsLabel.setTitleColor(UIColor.whiteColor(), forState: .Normal)
//背景カラー
buttonAsLabel.backgroundColor = UIColor.orangeColor()
//titleEdgeInsetsでpaddingができる
buttonAsLabel.titleEdgeInsets.left = 30
//ボタンとしての機能を停止→iOS7ではテキストが表示されなくなったのでやめます。
//buttonAsLabel.enabled = false

self.view.addSubview(buttonAsLabel)

ちなみに「アイコン+文字」みないなのもUIButtonが便利。

image

var buttonAsLabel2 = UIButton(frame: CGRectMake(100, 300, 200, 50))
//画像を設定
buttonAsLabel2.setImage(UIImage(named: "apple.png"), forState: .Normal)
buttonAsLabel2.setTitle("サンプルテキスト", forState: .Normal)
buttonAsLabel2.setTitleColor(UIColor.blackColor(), forState: .Normal)
//ボタンとしての機能を停止→iOS7ではテキストが表示されなくなったのでやめます。
// buttonAsLabel2.enabled = false
self.view.addSubview(buttonAsLabel2)
15
16
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
15
16