Riazbapoo Riazbapoo - 1 year ago 101
Swift Question

generating uisegmentedcontrol buttons with a loop

i am trying to generate sets of segmented control buttons from a loop if given an initial value.

so if the value is 3
i need the loop to generate 3 sets of segmented buttons below each other

this is what i have so far after unsuccessfully trying to adapt codes from tutorials.

var numberOfVillains = ["1", "2", "3", "4"]
var buttonY: CGFloat = 20 // our Starting Offset, could be 0
for number in numberOfVillains {
let segmentController = UISegmentedControl()
//let villainButton = UISegmentedControl(frame: CGRect(x: 50, y: buttonY, width: 50, height: 30)){
buttonY = buttonY + 50 // we are going to space these UIButtons 50px apart
segmentController.frame = CGRect(x:100, y:200, width: 200,height: 30)
//segment frame size
segmentController.insertSegment(withTitle: "1", at: 0, animated: true)
//inserting new segment at index 0
segmentController.insertSegment(withTitle: "2", at: 1, animated: true)
//inserting new segment at index 1
segmentController.backgroundColor = UIColor.blue
//setting the background color of the segment controller
segmentController.selectedSegmentIndex = 0
//setting the segment which is initially selected
segmentController.addTarget(self, action: "segment:", for: UIControlEvents.valueChanged)
//calling the selector method
//adding the view as subview of the segment comntroller w.r.t. main view controller

Answer Source

Every one of your segmented controller has the same frame, so they stack over each other. You have to use buttonY in :

segmentController.frame = CGRect(x:100, y:buttonY, width: 200,height:  30)

I think that you will see a difference

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download