Created
October 22, 2020 12:25
-
-
Save hfossli/3479fba9c701e855c032dc95e1fe1988 to your computer and use it in GitHub Desktop.
HideableView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension View { | |
func hide(_ hide: Bool) -> some View { | |
HideableView(isHidden: .constant(hide), view: self) | |
} | |
func hide(_ isHidden: Binding<Bool>) -> some View { | |
HideableView(isHidden: isHidden, view: self) | |
} | |
} | |
struct HideableView<Content: View>: UIViewRepresentable { | |
@Binding var isHidden: Bool | |
var view: Content | |
func makeUIView(context: Context) -> ViewContainer<Content> { | |
return ViewContainer(isContentHidden: isHidden, child: view) | |
} | |
func updateUIView(_ container: ViewContainer<Content>, context: Context) { | |
container.child.rootView = view | |
container.isContentHidden = isHidden | |
} | |
class ViewContainer<Content: View>: UIView { | |
var child: UIHostingController<Content> | |
var didShow = false | |
var isContentHidden: Bool { | |
didSet { | |
addOrRemove() | |
} | |
} | |
init(isContentHidden: Bool, child: Content) { | |
self.child = UIHostingController(rootView: child) | |
self.isContentHidden = isContentHidden | |
super.init(frame: .zero) | |
addOrRemove() | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
child.view.frame = bounds | |
} | |
func addOrRemove() { | |
if isContentHidden && child.view.superview != nil { | |
child.view.removeFromSuperview() | |
} | |
if !isContentHidden && child.view.superview == nil { | |
if !didShow { | |
DispatchQueue.main.async { | |
if !self.isContentHidden { | |
self.addSubview(self.child.view) | |
self.didShow = true | |
} | |
} | |
} else { | |
addSubview(child.view) | |
} | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wrote about this on
https://hfossli.medium.com/hiding-and-unhiding-views-in-swiftui-9474a839e5c9
and
https://hfossli.medium.com/lifecycle-bugs-in-swiftuis-tabview-c130b79d1cb