コードでボタンにアクションを追加する方法を忘れがちなのでメモ。
#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