LoginSignup
1
4

More than 5 years have passed since last update.

Swift備忘録~ボタンの実装編~

Last updated at Posted at 2018-01-25

はじめに

お仕事でStory Boardを使わずにボタンを実装することがあったので、今後も使えそうなのでここに記録します。
前回の投稿にも書いてありますが筆者の備忘録ですので、投稿の内容に過度な期待はしないでください。

環境

Xcode9.2

今回の備忘録

ボタンを実装するための必要最低限のコード

static func buttonMethod() -> UIButton {
          let button = UIButton()  //ボタンを定義 
          let height = CGFloat(○)   //ボタンの高さを定義、○の中に数値を入れる
          let width = CGFloat(○)       //ボタンの横幅を定義、○の中に数値を入れる
          button.backgroundColor = 〇〇  //ボタンの背景色を定義、○○の中に色を入れる
     return button
}

ボタンの中に画像を入れる

button.setImage(UIImage(named: "○○"), for: .normal)  //namedの部分に挿入したい画像の名前、forは最初の状態を入れる
button.imageInsets = UIEdgeInsets(top: ○, left: ○, bottom: ○, right: ○)  //ボタンの縁と画像の余白を定義、○の中に数値を入れる

ボタンの中にテキストを入れる

button.setTitle("○○", for: .normal)  //○○に入れたいテキスト、forは最初の状態を入れる
button.titleInsets = UIEdgeInsets(top: ○, left: ○, bottom: ○, right: ○)  //ボタンの縁とテキストの余白を定義、○の中に数値を入れる
button.setTitleColor(○○, for: .normal)  //○○にテキストの色、forは最初の状態を入れる

ボタンの中に画像とテキストの両方を挿入したいときは、表示される位置に注意。これを書けば右側に画像、左側にテキストが表示できるようになる。

button.semanticContentAttribute = .forceRightToLeft

文字数でボタンの横幅を変える

button.sizeToFit()

ボタンの角を丸める

button.layer.cornerRadius = ○  //○の中に数値を入れる

タップされた時のボタンの色の設定

button.setTitleColor(○○, for: .highlighted)  //タップされた時のボタンの文字の色を決める、○○の中に色を入れる
button.setBackgroundImage(createImageFromUIColor(color: ○○), for: .highlighted)  //タップされた時のボタンの画像の背景色を決める、○○の中に色を入れる

ボタンが非活性時の色の設定

button.setTitleColor(○○, for: .disabled)  //非活性時のボタンの文字の色を決める、○○の中に色を入れる
button.setBackgroundImage(createImageFromUIColor(color: ○○), for: .disabled)  //非活性時のボタンの画像の背景色を決める、○○の中に色を入れる

createImageFromUIColor(color: ○○)は、これは作られたメソッドなのでそのままコピペしてもエラーになるだけなので、UIColorからUIImageを作るメソッドを作る。このメソッドの意義、実はちゃんとわかってない。

static func createImageFromUIColor(color: UIColor) -> UIImage? {
     let rect = CGRect(x: ○, y: ○, width: ○, height: ○)  //width * height の bitmapを作成、○に数字を入れる
     UIGraphicsBeginImageContext(rect.size)
     let context = UIGraphicsGetCurrentContext()
     context?.setFillColor(〇〇)  //〇〇に色を入れる
     context?.fill(rect)  //bitmapを塗りつぶす
          let image = UIGraphicsGetImageFromCurrentImageContext()  //UIImageに変換
     UIGraphicsEndImageContext()
     return image
}
1
4
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
1
4