Tuesday 7 March 2017

UISegmentControl



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

import UIKit

class ViewController: UIViewController {
    
    private let mySegLabel: UILabel = UILabel(frame: CGRectMake(0,0,150,150))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // make an array for labels on segmentedControl
        let myArray: NSArray = ["Red","Blue","Green"]
        
        // make SegmentedControl
        let mySegcon: UISegmentedControl = UISegmentedControl(items: myArray as [AnyObject])
        mySegcon.center = CGPoint(x: self.view.frame.width/2, y: 400)
        mySegcon.backgroundColor = UIColor.grayColor()
        mySegcon.tintColor = UIColor.whiteColor()
        
        // add an event for valueChanged.
        mySegcon.addTarget(self, action: "segconChanged:", forControlEvents: UIControlEvents.ValueChanged)
        
        // add the segmentedControl to the view
        self.view.addSubview(mySegcon)
        
        // make uilabel to change the color when the value of SegmentedControl is changed.
        mySegLabel.backgroundColor = UIColor.whiteColor()
        mySegLabel.layer.masksToBounds = true
        mySegLabel.textColor = UIColor.whiteColor()
        mySegLabel.shadowColor = UIColor.grayColor()
        mySegLabel.font = UIFont.systemFontOfSize(CGFloat(30))
        mySegLabel.textAlignment = NSTextAlignment.Center
        mySegLabel.layer.position = CGPoint(x: self.view.bounds.width/2,y: 200)
        
        self.view.backgroundColor = UIColor.blackColor()
        
        self.view.addSubview(mySegLabel);
    }
    
    // called when the value of SegmentedControl is changed.
    internal func segconChanged(segcon: UISegmentedControl){
        
        switch segcon.selectedSegmentIndex {
        case 0:
            mySegLabel.backgroundColor = UIColor.redColor()
            
        case 1:
            mySegLabel.backgroundColor = UIColor.blueColor()
            
        case 2:
            mySegLabel.backgroundColor = UIColor.greenColor()
            
        default:
            print("Error")
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

No comments:

Post a Comment