【问题标题】:generating uisegmentedcontrol buttons with a loop生成带有循环的uisegmentedcontrol按钮
【发布时间】:2016-10-05 22:07:30
【问题描述】:

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

所以如果值为 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
    }

【问题讨论】:

    标签: ios swift loops for-loop uisegmentedcontrol


    【解决方案1】:

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

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

    我认为你会看到不同

    【讨论】:

    • 正确,谢谢。现在我只需要弄清楚为什么当我点击生成的按钮时应用程序崩溃:)
    • 显然您没有为这些 SC 指定委托,您应该穿上并设置委托方法。但我不明白为什么如果你没有设置它们会崩溃......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多