swift 如何隐藏导航栏向下滚动,当约束是编程?

lc8prwob  于 2023-05-16  发布在  Swift
关注(0)|答案(1)|浏览(151)

我所有的UI都是通过编程来实现的,为了避免一个庞大的视图控制器,我有一个类型为UIView的类,在那里我声明了所有的UI元素。
我这样声明我的scrollView:

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)
        ])      
   }
}

宣言之后。我在ViewController中创建了一个RegisterUIView示例。在viewWillAppearviewWillDisappear中,我使用了变量hidesBarsOnSwipe来隐藏导航栏。当我向下滚动时,该栏隐藏,但当我向上滚动时,该栏不会取消隐藏。
我在另一个问题here中读到,我需要将top约束设置为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)
        ])
    }
gojuced7

gojuced71#

在添加约束之前将滚动视图添加到子视图。您的应用崩溃是因为您正在向对象(而不是在子视图中)添加约束。

view.addSubview(scrollView)

在开始添加约束之前,将这行代码添加到setupLayout()函数的顶部。

相关问题