開発環境
Swift 4
Xcode 9.2
ポイント
UIButtonの追加
sample.swift
let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
button.backgroundColor = .black
button.setTitle("sample", for: .normal)
button.setTitleColor(.white, for: .normal)
self.view.addSubview(button)
UIButtonを押すと、発火するfunc
func
の前に @objc
を追加
sample.swift
@objc func pushButton(sender: UIButton){
print("button pushed.")
}
UIButtonとfuncの紐付け
sample.swift
let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
button.backgroundColor = .black
button.setTitle("sample", for: .normal)
button.setTitleColor(.white, for: .normal)
//追加したコード
button.addTarget(self, action: #selector(pushButton), for: .touchUpInside)
self.view.addSubview(button)
コード例
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button:UIButton = UIButton(frame: CGRect(x: 0, y: 50, width: self.view.frame.width, height: self.view.frame.height / 4))
button.backgroundColor = .black
button.setTitle("sample", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(pushButton), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func pushButton(sender: UIButton){
print("button pushed.")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}