使用swift以编程方式填充UISegmentedControl

时间:2016-09-26 23:19:38

标签: ios swift swift3 uisegmentedcontrol

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

如果我没有误会,您的意思是您希望以编程方式将段添加到“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)")
    }
}

答案 2 :(得分:0)

我使用@ 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)

    }


}