StoryBoardを使わずに、UISwitchを実装する方法
Q. なぜ、StoryBoardを使わないのか?
A. GitHubで管理している場合、コンフリクトが発生するため。
開発環境
Swift 4
Xcode 9.2
ポイント
UISwitech の追加
sample.swift
let sample_switch:UISwitch = UISwitch(frame: CGRect(x: (self.view.frame.width) / 2, y: (self.view.frame.height) / 2 , width: 50, height: 25))
self.view.addSubview(sample_switch)
UISwitchを切り替えると、発火するfunc
func
の前に @objc
を追加
sample.swift
var index:Int = 1
@objc public func sampleSwitch(sender: UISwitch){
print("\(index) times switched")
index += 1
}
UISwitchとfuncの紐付け
sample.swift
let sample_switch:UISwitch = UISwitch(frame: CGRect(x: (self.view.frame.width) / 2, y: (self.view.frame.height) / 2 , width: 50, height: 25))
//追加したコード
sample_switch.addTarget(self, action: #selector(sampleSwitch), for: UIControlEvents.valueChanged)
self.view.addSubview(sample_switch)
コード例
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sample_switch:UISwitch = UISwitch(frame: CGRect(x: (self.view.frame.width) / 2, y: (self.view.frame.height) / 2 , width: 50, height: 25))
sample_switch.addTarget(self, action: #selector(sampleSwitch), for: UIControlEvents.valueChanged)
self.view.addSubview(sample_switch)
}
var index:Int = 1
@objc public func sampleSwitch(sender: UISwitch){
print("\(index) times switched.")
index += 1
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
シュミレータ実行結果
Xcode
1 times switched.
2 times switched.
3 times switched.