0

我正在以编程方式完成所有 UI,为了避免庞大的视图控制器,我有一个 UIView 类型的类,我在其中声明了所有 UI 元素。

我像这样声明我的滚动视图:

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 实例。并且在viewWillAppearandviewWillDisappear我使用了变量hidesBarsOnSwipe, 来隐藏导航栏。当我向下滚动时,栏隐藏,但当我向上滚动时,栏并没有隐藏。

我在这里读到其他问题,我需要将顶部约束设置为超级视图。如何设置超级视图的约束?,当我尝试设置它时,应用程序崩溃,显然是因为没有超级视图。

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

4

1 回答 1

0

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

view.addSubview(scrollView)

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

于 2020-06-30T00:28:32.637 回答