iphoneアプリ開発で必ず使用するUIボタン。
今回はUIボタンに
- 文字色
- 高さ
- 幅
- 位置調整
- 背景色
- ボーダー
- 角丸
- シャドウ(影)
などの装飾を施す方法を紹介します!
Object LibraryからButtonを選択して、Storyboardに配置する

まずは、装飾するボタンを配置しましょう。
配置が完了したら、ViewControllerに紐づけます。(Control + ドラッグ・アンド・ドロップ)
swiftのソースでボタンを装飾していく
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import UIKit class ViewController: UIViewController { @IBOutlet var button: UIButton! override func viewDidLoad() { super.viewDidLoad() button.frame = CGRect(x: 100, y: 100, width: 200, height: 200) // 1 button.center = self.view.center // 2 button.backgroundColor = .red // 3 button.setTitleColor(UIColor.white, for: UIControl.State.normal) // 4 button.layer.borderWidth = 4 // 5 button.layer.borderColor = UIColor.blue.cgColor // 6 button.layer.cornerRadius = 10 // 7 button.layer.shadowOffset = CGSize(width: 3, height: 3 ) // 8 button.layer.shadowOpacity = 0.5 // 9 button.layer.shadowRadius = 10 // 10 button.layer.shadowColor = UIColor.gray.cgColor // 11 } } |
ViewControllerをこの状態にして、ビルドすると

こういった形で、
- 大きさ
- 位置
- 背景色
- 文字色
- ボーダー幅
- ボーダー色
- 角丸
- 影
が装飾されたボタンが完成します。
ソースのどこの部分でどの装飾を施しているかを説明すると、
- 大きさと位置
- 位置(センター寄せにさせるために1を上書き)
- 背景色
- 文字色
- ボーダー幅
- ボーダー色
- 角丸の度合い
- 影の大きさ
- 影の薄さ
- 影の丸み
- 影の色
を設定しています。(ソースのコメントアウトの数字に対応)
こういった形で、swiftではボタンの装飾を行います!