I'm doing all my UI programatically, to avoid a massive view controller I have a class of type UIView where I'm declaring all my UI elements.
I'm declaring my scrollView like this:
class RegisterUIView: UIView {
lazy var scrollView: UIScrollView = {
let scroll: UIScrollView = UIScrollView()
scroll.contentSize = CGSize(width: self.frame.size.width, height: self.frame.size.height)
scroll.translatesAutoresizingMaskIntoConstraints = false
return scroll
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: self.topAnchor),
scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
}
}
After the declaration. I create an instance of RegisterUIView in my ViewController.
And in the viewWillAppear
and viewWillDisappear
I used the variable hidesBarsOnSwipe
, to hide the navigation bar.
When I scroll down the bar hides, but when I scroll up the bar is not unhiding.
I read in other question here that I need to set the top constraint to the superview. How can is set the constraints to the superview?, when I try to set it the app crashes, and is obviously because there is no superview.
class RegisterViewController: UIViewController {
private let registerView: RegisterUIView = {
let view: RegisterUIView = RegisterUIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.hidesBarsOnSwipe = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.hidesBarsOnSwipe = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
}
func setupLayout() {
view.addSubview(registerView)
NSLayoutConstraint.activate([
registerView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
registerView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
registerView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor),
registerView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor)
])
}