0
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 3 years have passed since last update.

UIButtonにコードでアクションを追加する方法

Posted at

コードでボタンにアクションを追加する方法を忘れがちなのでメモ。
#selector@objc などObjective-Cのコードを使用します。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let lightGray = UIColor.init(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)

        let button = UIButton(type: .roundedRect)
        button.backgroundColor = lightGray
        button.setTitle("Button1", for: .normal)
        button.frame = CGRect(x: 100, y: 100, width: 100, height: 40)
        // アクションの追加
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)


        view.addSubview(button)
    }

    @objc func buttonTapped(){
        print("buttonTapped called")
    }

}

viewが読み込まれるタイミングで、以下のように書きます。

ボタン.addTarget(どのViewControllerか, action: #selector(アクション(_:)), for: タップの種類)

そして@objcという修飾子をつけてメソッドを書けばOK

参考:
https://swift-ios.keicode.com/ios/target-action.php

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