使用Swift编程自动填充UISegmentedControl

5

是否可以使用Swift编程以编程方式填充UISegmentedControl的值?

3个回答

13

就这样做:

let segmentedControl = UISegmentedControl()
segmentedControl.insertSegment(withTitle: "Title", at: 0, animated: true)
segmentedControl.setTitle("Another Title", forSegmentAt: 0)

请记住,插入片段和更新标题应始终在主线程上完成。如果尚未将其添加到视图中,则同样适用于将其添加到视图中。


6

如果我没理解错的话,您想以编程的方式向“UISegmentedControl”组件添加段,而不使用Interface Builder。

是的,这是可能的:

// 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)")
    }
}

1

我解决了我的问题,使用了@RyuX51的解决方案,现在我的代码是:

class MyCustomViewController: UIViewController{

    @IBOutlet weak var ServicesSC: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()

        ServicesSC.removeAllSegments()


        ServicesSC.insertSegment(withTitle: "Title", at: 0, animated: true)
        ServicesSC.setTitle("Another Title", forSegmentAt: 0)

    }


}

请记得以小写字母开头命名变量,如果您没有在viewDidLoad(在主线程上运行)中执行这些步骤,请记得调度到主线程。 - RyuX51

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接