Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill programmatically UISegmentedControl using swift

Is possible fill the values of a UISegmentedControl programmatically using swift?

like image 795
Benjamin RD Avatar asked Sep 26 '16 23:09

Benjamin RD


2 Answers

let segmentedControl = UISegmentedControl()
segmentedControl.insertSegment(withTitle: "Title", at: 0, animated: true)
segmentedControl.setTitle("Another Title", forSegmentAt: 0)
like image 59
RyuX51 Avatar answered Oct 17 '22 00:10

RyuX51


If I am not mistaking, you mean that you want to add segments to "UISegmentedControl" component programmatically, without using the Interface Builder.

Yes, it is possible:

// Assuming that it is an "IBOutlet", you can do this in your "ViewController":
class ViewController: UIViewController {

    @IBOutlet weak var segmentedControl: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()

        // remove all current segments to make sure it is empty:
        segmentedControl.removeAllSegments()

        // adding your segments, using the "for" loop is just for demonstration:
        for index in 0...3 {
           segmentedControl.insertSegmentWithTitle("Segment \(index + 1)", atIndex: index, animated: false)
        }

        // you can also remove a segment like this:
        // this removes the second segment "Segment 2"
        segmentedControl.removeSegmentAtIndex(1, animated: false)
    }

    // and this is how you can access the changing of its value (make sure that event is "Value Changed")
    @IBAction func segmentControlValueChanged(sender: UISegmentedControl) {
        print("index of selected segment is: \(sender.selectedSegmentIndex)")
    }
}
like image 38
Ahmad F Avatar answered Oct 17 '22 00:10

Ahmad F