LoginSignup
4
5

More than 5 years have passed since last update.

[Swift/iOS]StoryBoardを使わずに、UISwitchを実装する方法

Last updated at Posted at 2018-01-24

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.
4
5
2

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
4
5