简体   繁体   中英

Fill programmatically UISegmentedControl using swift

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

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

If I am not mistaking, you mean that you want to add segments to "UISegmentedControl" component programmatically, without using the Interface Builder.

Yes, it is possible:

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

I resolved my problem, using the solution of @RyuX51 and my code now is:

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)

    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM