Saturday 4 March 2017

Switch Dynamic



//
//  ViewController.swift
//  TestApp1
//
//  Created by Divakar Singh on 3/1/17.
//  Copyright (c) 2017 Divakar Singh. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    var lbl1 :UILabel!
    var sw1 : UISwitch!
    var sw2 : UISwitch!
    var btn1 : UIButton!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // create Label
        lbl1 = UILabel()
        lbl1.sizeToFit()
        lbl1.frame = CGRect(x: 100, y: 50, width: 300, height: 36)
        lbl1.text = "Default Label"
        lbl1.backgroundColor = UIColor.grayColor()
        view.addSubview(lbl1)
        
        // create switch 1
        sw1 = UISwitch()
        sw1.sizeToFit()
        sw1.center = CGPoint(x: 100, y: 150)
        sw1.addTarget(self, action: "getStatus:", forControlEvents: UIControlEvents.ValueChanged)
        
        view.addSubview(sw1)
        
        // create switch 2
        sw2 = UISwitch()
        sw2.sizeToFit()
        sw2.center = CGPoint(x: 200, y: 150)
        sw2.onTintColor = UIColor.purpleColor()
        sw2.tintColor = UIColor.redColor()
        sw2.thumbTintColor = UIColor.orangeColor()
        view.addSubview(sw2)
    
        // create switch 2
        btn1 = UIButton()
        btn1.sizeToFit()
        btn1.center = CGPoint(x: 100, y: 225)
        btn1.titleLabel?.text = "ON/OFF"
        btn1.backgroundColor = UIColor.greenColor()
        btn1.addTarget(self, action: "changeSwitchState:", forControlEvents: UIControlEvents.TouchUpInside)
        
        view.addSubview(btn1)
    }
    func getStatus(sender : UISwitch)
    {
        if sender.on{ lbl1.text = "ON State" }
        else { lbl1.text = "OFF State" }
        
    }
    
    func changeSwitchState(sender : UIButton)
    {
        if sw1.on == true{
             lbl1.text = "ON State"
            sw1.setOn(false, animated: true)
        }else{
            lbl1.text = "OFF State"
            sw1.setOn(true, animated: true)
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}


No comments:

Post a Comment