使用循环生成 uisegmentedcontrol 按钮

generating uisegmentedcontrol buttons with a loop

如果给定初始值,我正在尝试从循环中生成多组分段控制按钮。

所以如果值为 3 我需要循环在彼此下方生成 3 组分段按钮

这是我在尝试改编教程中的代码失败后到目前为止所拥有的。

    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
        self.view.addSubview(segmentController)
        //adding the view as subview of the segment comntroller w.r.t. main view controller
    }

您的每个分段控制器都具有相同的框架,因此它们相互堆叠。您必须在 :

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

我想你会看到不同