Nazir Doğan Code Blog

Programmatically Creating UI Elements Using Swift 3

| Comments

if you are new in iOS development and using Interface Builder for creating UI elements. Maybe you want to learn how can do with code. In this post I will talk about this and give a snippet.

UIView

1
2
3
let child = UIView(frame: CGRect(x: 100, y: 100,width:100, height: 100))
child.backgroundColor = UIColor.red
self.view.addSubview(child)

UISlider

1
2
3
4
5
6
7
8
 let slider = UISlider (frame: CGRect(x: 10, y: 300,width:300, height: 100))
     slider.minimumValue = 0
     slider.maximumValue = 100
     slider.tintColor = UIColor.red
     slider.isContinuous = true
     slider.value = 30
     slider.addTarget(self, action:#selector(sliderValueDidChange), for: .valueChanged)
     self.view.addSubview(slider)
1
2
3
4
func sliderValueDidChange(sender:UISlider!)
   {
      print("value : \(sender.value)")
   }

UIButton

1
2
3
4
5
let button  = UIButton (frame : CGRect (x:100, y:100 ,width:100 , height:40))
    button.backgroundColor = UIColor.red
    button.setTitle("My Button", for:.normal)
    button.setTitleColor(UIColor.yellow, for: .normal)
   self.view.addSubview(button)
1
 button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)

UISwitch

1
2
3
4
let switchDemo = UISwitch(frame: CGRect(x:100, y:100 ,width:40, height:40))
    switchDemo.isOn  = true
    switchDemo.addTarget(self, action: #selector(switchChanged), for: .valueChanged)
    self.view.addSubview(switchDemo)
1
2
3
4
func switchChanged(sender: UISwitch!){

      print("value: \(sender.isOn)")
  }

UISegmentedControl

1
2
3
4
5
6
7
let segmentedControl = UISegmentedControl(frame: CGRect(x:10, y:100 ,width:260, height:30))
    segmentedControl.insertSegment(withTitle:"index 0", at: 0, animated: false)
    segmentedControl.insertSegment(withTitle:"index 1", at: 1, animated: false)
    segmentedControl.insertSegment(withTitle:"index 2", at: 2, animated: false)
    segmentedControl.addTarget(self, action: #selector(getSegmentedControlValue), for: .valueChanged)
    segmentedControl.selectedSegmentIndex = 0
    self.view.addSubview(segmentedControl)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func getSegmentedControlValue(sender:UISegmentedControl!) {
       if  sender.selectedSegmentIndex == 0 {
           print("index 0")

       }
       else if sender.selectedSegmentIndex == 1 {

           print("index 1")

       }
       else {
           print("index 2")
       }

   }

Comments