標準で用意されているsystemImageを使って、以下のような追加ボタンを作る。
StoryBoardでImageに「plus」を設定して、テキストは消す。
systemImageのサイズ、色はコードで設定する。
以下の3行で、ボタンいっぱいに画像を表示させることができる。
button.imageView?.contentMode = .scaleAspectFit
button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
大きすぎる場合は、.imageEdgeInsetsでマージンを調整できる。
button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10);
すべてのコード
import UIKit class ViewController: UIViewController { @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() //角丸 button.layer.cornerRadius = 20 //画像の色 button.imageView?.tintColor = .white //ボタンいっぱいに画像を表示する button.imageView?.contentMode = .scaleAspectFit button.contentHorizontalAlignment = .fill button.contentVerticalAlignment = .fill //画像にマージンを追加する button.imageEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10); } }
完成