Adding a Segmented Control Programmatically Swift 4

A horizontal control made of multiple segment. Each segment has its own function. 




Initialization UISegmentControl 
override func viewDidLoad() {
     super.viewDidLoad()
     let items = ["iOS" , "Android"]
     let segmentedControl = UISegmentedControl(items : items)
     segmentedControl.center = self.view.center
     segmentedControl.selectedSegmentIndex = 0
     segmentedControl.addTarget(self, action: #selector(ViewController.indexChanged(_:)), for: .valueChanged)

     segmentedControl.layer.cornerRadius = 5.0  
     segmentedControl.backgroundColor = .red
     segmentedControl.tintColor = .yellow

     self.view.addSubview(segmentedControl)
  }
Action handler of UISegmentControl 
@objc func indexChanged(_ sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex{
        case 0:
            print("iOS");
        case 1:
            print("Android")
        default:
            break
        }
}


Output 





Adding a Segmented Control Programmatically Swift 4 Adding a Segmented Control Programmatically Swift 4 Reviewed by KIRIT MODI on 06:33:00 Rating: 5

No comments:

Powered by Blogger.