When you select a segment on the first control, you want to remove all current segments from the second control and then insert new segments.
Here's a simple example - with a new view controller, add two UISegmentedControl
objects, and connect them via IBOutlet
. Leave them at the default "First, Second" segments -- we'll be changing those via code:
class DynamicSegmentsViewController: UIViewController {
@IBOutlet var firstSegControl: UISegmentedControl!
@IBOutlet var secondSegControl: UISegmentedControl!
let cities: [String] = [
"Lexington",
"Chengdu",
"Chicago",
"Hongkong",
]
let places: [[String]] = [
["Keeneland", "Arboretum"],
["Place 1", "Place 2", "Place 3"],
["Millenium", "Skydeck", "Cruise", "Planetarium"],
["HK 1", "HK 2", "HK 3", "HK 4", "HK 5", "HK 6"]
]
override func viewDidLoad() {
super.viewDidLoad()
firstSegControl.removeAllSegments()
for i in 0..<cities.count {
firstSegControl.insertSegment(withTitle: cities[i], at: i, animated: false)
}
firstSegControl.selectedSegmentIndex = 0
updateSecondSegControl(0)
}
func updateSecondSegControl(_ n: Int) -> Void {
secondSegControl.removeAllSegments()
for i in 0..<places[n].count {
secondSegControl.insertSegment(withTitle: places[n][i], at: i, animated: false)
}
secondSegControl.selectedSegmentIndex = 0
}
@IBAction func locationChoiceIsMade(_ sender: UISegmentedControl) {
updateSecondSegControl(sender.selectedSegmentIndex)
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…