I am attempting to use an UISegmentedControl to switch between three views. I have the first view within a container view on the main viewcontroller. I then created two other views on separate viewcontrollers. I programmed subviews for these two views within the main viewcontroller's container.
The issue I'm having is that the second two views won't show up when I switch the segmented control. The segment changes the container and hides the first view but the second two are not appearing.
I was able to use this method when I had the second two views created through .xib files. Problem is now I have them as viewcontrollers on the storyboard instead.
Here is the code:
@IBOutlet var segment: UISegmentedControl!
@IBOutlet var detailsView: UIView!
@IBOutlet var segmentView: UIView!
var viewTwo: UIView!
var viewThree: UIView!
@IBAction func segmentChange(_ sender: Any) {
switch(segment.selectedSegmentIndex) {
case 0:
detailsView.isHidden = false
segmentView.isHidden = true
break
case 1:
detailsView.isHidden = true
segmentView.isHidden = false
segmentView.bringSubviewToFront(viewTwo)
break
case 2:
detailsView.isHidden = true
segmentView.isHidden = false
segmentView.bringSubviewToFront(viewThree)
break
default:
detailsView.isHidden = false
segmentView.isHidden = true
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewTwo = ShowtimesView().view
segmentView.addSubview(viewTwo)
viewThree = ReviewsView().view
segmentView.addSubview(viewThree)
}
I solved this by creating a container for each of the subview viewcontrollers in the original viewcontroller. I also made sure to add the proper names to their storyboard id's not only their classes.
Here is the working code:
@IBOutlet var segment: UISegmentedControl!
@IBOutlet var detailsView: UIView!
@IBOutlet var showtimeView: UIView!
@IBOutlet var reviewView: UIView!
var viewTwo: UIView!
var viewThree: UIView!
@IBAction func segmentChange(_ sender: Any) {
switch(segment.selectedSegmentIndex) {
case 0:
detailsView.isHidden = false
showtimeView.isHidden = true
reviewView.isHidden = true
break
case 1:
detailsView.isHidden = true
showtimeView.isHidden = false
reviewView.isHidden = true
break
case 2:
detailsView.isHidden = true
showtimeView.isHidden = true
reviewView.isHidden = false
break
default:
detailsView.isHidden = false
showtimeView.isHidden = true
reviewView.isHidden = true
break
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewTwo = ShowtimesView().view
showtimeView.addSubview(viewTwo)
viewThree = ReviewsView().view
reviewView.addSubview(viewThree)
}