I\'m trying to update a UIStackView
so that a field displays, should the value of a UITextField
equal \"Other\"
. Here is my code:
try to manipulate alpha along with isHidden property:
self.stackView.arrangedSubviews[3].isHidden = true
self.stackView.arrangedSubviews[3].alpha = 0
self.stackView.arrangedSubviews[3].isHidden = false
self.stackView.arrangedSubviews[3].alpha = 1
Updates on the user interface always have to be done on the main thread (THE LAW).
So wrap you UI updates on the main thead:
@IBOutlet var stackView: UIStackView!
func updateView() {
print("UPDATING")
UIView.animate(withDuration: 0.25, animations: { () -> Void in
DispatchQueue.main.async { // UI updates on the main thread
if(self.myTextField.text! == "Other") {
print("SHOWING")
self.stackView.arrangedSubviews[3].isHidden = false
} else {
print("HIDING")
self.stackView.arrangedSubviews[3].isHidden = true
}
print("Is hidden: \(self.stackView.arrangedSubviews[3].isHidden )")
}
})
It's known UIStackView
bug (http://www.openradar.me/25087688). There is a thread on SO about it: (Swift: Disappearing views from a stackView). Long story short:
The bug is that hiding and showing views in a stack view is cumulative. Weird Apple bug. If you hide a view in a stack view twice, you need to show it twice to get it back.
To fix this issue you can use following extension:
extension UIView {
var isHiddenInStackView: Bool {
get {
return isHidden
}
set {
if isHidden != newValue {
isHidden = newValue
}
}
}
}