TaillookTech

モバイルアプリ開発を追っています

Swift UIButtonをコードのみで作る

備忘録

環境

  • Swift4
  • Xcode9

コード

let button = UIButton()
//表示されるテキスト
button.setTitle("Tap Me!", for: .normal)
//テキストの色
button.setTitleColor(UIColor.blue, for: .normal)
//タップした状態のテキスト
button.setTitle("Tapped!", for: .highlighted)
//タップした状態の色
button.setTitleColor(UIColor.red, for: .highlighted)
//サイズ
button.frame = CGRect(x: 0,y: 0,width: 300,height: 50)
//タグ番号
button.tag = 1
//配置場所
button.layer.position = CGPoint(x: view.frame.width / 2, y: view.bounds.height / 2)
//背景色
button.backgroundColor = UIColor.white
//角丸
button.layer.cornerRadius = 10
//ボーダー幅
button.layer.borderWidth = 1
//ボタンをタップした時に実行するメソッドを指定
button.addTarget(self, action: #selector(self.buttonTapped), for:.touchUpInside)
view.addSubview(button)