You need to think about your data when you're getting started.
Presumably, you'll either have a database or you'll be pulling the information from a remote server.
You might have a data structure like this:
struct Place {
var placeName: String = ""
var imgName: String = ""
}
struct City {
var cityName: String = ""
var places: [Place] = []
}
Then, you'd create a data array:
var cities: [City] = []
and you'd fill the array:
var somePlace: [Place]!
var aPlace: Place!
var aCity: City!
// Lexington
somePlace = []
aPlace = Place(placeName: "Keeneland", imgName: "KeenelandPicture")
somePlace.append(aPlace)
aPlace = Place(placeName: "Arboretum", imgName: "ArboretumPicture")
somePlace.append(aPlace)
aCity = City(cityName: "Lexington", places: somePlace)
cities.append(aCity)
// Chengdu
somePlace = []
aPlace = Place(placeName: "Place 1", imgName: "Place1Picture")
somePlace.append(aPlace)
aPlace = Place(placeName: "Place 2", imgName: "Place2Picture")
somePlace.append(aPlace)
aCity = City(cityName: "Chengdu", places: somePlace)
cities.append(aCity)
// and so on
Now, to fill your first segmented control:
firstSegControl.removeAllSegments()
for i in 0..<cities.count {
let aCity = cities[i]
firstSegControl.insertSegment(withTitle: aCity.cityName, at: i, animated: false)
}
and to fill your second segmented control:
func updateSecondSegControl(_ n: Int) -> Void {
secondSegControl.removeAllSegments()
let aCity = cities[n]
let places = aCity.places
for i in 0..<places.count {
let aPlace = places[i]
secondSegControl.insertSegment(withTitle: aPlace.placeName, at: i, animated: false)
}
secondSegControl.selectedSegmentIndex = 0
}
and to set your image when the second segmented control is changed:
let aCity = cities[firstSegControl.selectedSegmentIndex]
let places = aCity.places
let aPlace = places[secondSegControl.selectedSegmentIndex]
if let img = UIImage(named: aPlace.imgName) {
locationImageView.image = img
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…