1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【超初心者向け】UIButtonについて

Last updated at Posted at 2023-03-04

最初に

この記事はswiftを勉強し始めた超初心者による超初心者のためのものになっているので、細かいミスなどが散見されるかもしれませんがご了承ください。

buttonとactionの結びつけ

buttonと何らかのActionを結びつける方法は二つあります。(多分)

1.@IBActionを使用する方法
@IBAction func print(){
   print("ボタンが押されました")
}

@IBActionで宣言した関数はstoryboard上でbuttonと関連付けができるので、それを行ってactionを使用する方法です。buttonをどんな感じで押したときにactionがされるのかっていうのはstoryboard上で関連付けを行うときに決定します(touchUpInsideとか)。

2.@objcを使用する方法
@IBOutlet var button: UIButton!

override func viewDidLoad() {
   super.viewDidLoad()

   button.addTarget(target: self, action: #selector(print(_:)), for: UIControl.Event.touchUpInside)
}

@objc func print(_ sender: Any){
   print("ボタンが押されました")
}

@objc func で宣言した関数を addTargetbutton にコード上で結びつける方法です。この場合、buttonaction の関連付けはコード上で行っているので、必要になる関連付けはUIパーツの button の関連付けです。
addTarget の中身については、target は基本的に selfaction の中に #selector(関数名(sender)) っていう形でそのボタンが押されたときの action となる関数を記述し、for にはどんなタッチイベントのときに起動するのかということを設定します。細かい話は別の記事を見てください。
ちなみに、このやり方はGestureRecognizer などを使用するときにも使えます。

senderについて
@IBAction func print(_ sender: Any){
}

@IBAction func print(_sender: UIButton){
}

@IBAction  func print(){
}

基本的には上のどれでもいけます。ただ @objcaddTarget を使用する場合は sender を未設定でいくとダメみたいです。

buttonのカスタマイズ

@IBOutlet var button: UIButton!

override func viewDidLoad() {
   super.viewDidLoad()

   //ボタンの背景色を変える
   button.backgroundColor = .red

   //ボタンの文字を設定する
   button.setTitle("タイトル", for: .normal)

   //ボタンのフォント、文字サイズを設定する
   button.titleLabel?.font = UIFont(name: "フォントの名前", size: 20)

   //ボタンの文字色を変える
   button.tintColor = .blue

   //ボタンに画像を設定する
   button.setImage(UIImage(named: "画像の名前"), for: .normal)

   //ボタンに枠線をつける(枠線の太さを変える)
   button.layer.borderWidth = 3.0

   //ボタンの枠線の色を変える
   button.layer.borderColor = UIColor.black.cgColor

   //ボタンの枠線の丸みを変える
   button.layer.cornerRadius = 5.0

   //ボタンに影の明瞭さを変える
   button.layer.shadowOpacity = 0.7

   //ボタンの影の丸みを変える
   button.layer.shadowRadius = 3

   //ボタンの影の色を変える
   button.layer.shadowColor = UIColor.black.cgColor

   //ボタンと影の離れ具合を設定する
   button.layer.shadowOffset = CGSize(width: 5, height: 5)   
}

最後に

いろいろとミスってるところとかあると思うので、ご指摘お願いします。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?