Swift: Disappearing views from a stackView
ios, iphone, swift, uistackview
Solution
In the end, after trying all the suggestions here I still couldn't work out why it was behaving like this so I got in touch with Apple who asked me to file a bug report. I did however find a work around, by unhiding both views first, which solved my problem:
func updateView(segment: String) {
UIView.animate(withDuration: 1) {
self.stackView.arrangedSubviews[1].isHidden = false
self.stackView.arrangedSubviews[2].isHidden = false
if(segment == "First") {
self.stackView.arrangedSubviews[2].isHidden = true
} else {
self.stackView.arrangedSubviews[1].isHidden = true
}
}
}
Problem
I have a fairly simple set up in my main storyboard: - A stack view which includes three views - The first view has a fixed height and contains a segment controller - The other two views have no restrictions, the idea being that only one will be active at a time and thus fill the space available I have code that will deal with the changing view active views as follows: ``` import Foundation import UIKit class ViewController : UIViewController { @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var segmentController: UISegmentedControl! @IBAction func SegmentClicked(_ sender: AnyObject) { updateView(segment: sender.titleForSegment(at: sender.selectedSegmentIndex)!) } override func viewDidLoad() { updateView(segment: "First") } func updateView(segment: String) { UIView.animate(withDuration: 1) { if(segment == "First") { self.stackView.arrangedSubviews[1].isHidden = false self.stackView.arrangedSubviews[2].isHidden = true } else { self.stackView.arrangedSubviews[1].isHidden = true self.stackView.arrangedSubviews[2].isHidden = false } print("Updating views") print("View 1 is \(self.stackView.arrangedSubviews[1].isHidden ? "hidden" : "visible")") print("View 2 is \(self.stackView.arrangedSubviews[2].isHidden ? "hidden" : "visible")") } } } ``` As you can see, when the tab called 'First' is selected, the subview at index 1 should show, whilst 2 is hidden, and when anything else is selected, the subview at index 2 should show, whilst 1 is hidden. This appears to work at first, if I go slowly changing views, but if I go a bit quicker, the view at index 1 seems to remain permanently hidden after a few clicks, resulting in the view at index 0 covering the whole screen. I've placed an animation showing the issue and a screenshot of the storyboard below. The output shows that when the problem happens, both views remain hidden when clicking on the first segment. Can anybody tell me why this is happening? Is this a bug, or am I not doing something I should be? Many thanks in advance! Update: I seem to be able to reliably reproduce the issue by going to the First > Second > Third > Second > First segments in that order.