uiview 优于 uinavigationcontroller

uiview over uinavigationcontroller

我在导航控制器下添加 uiview 时遇到问题。为什么我的 uiview 在 uinavigationcontroller 之上,我想在 navigationController 下添加我的 uiview。 这是我的代码。

let slideView = UIView()

view.backgroundColor = .white
        navigationItem.title = "Absensi"
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationController?.navigationBar.barTintColor = .white
        navigationController?.navigationBar.shadowImage  = UIImage()
        navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "NunitoSans-SemiBold", size: 20)]
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic-back-line").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleBack))


view.addSubview(slideView)
        slideView.backgroundColor = .red
        slideView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            slideView.topAnchor.constraint(equalTo: view.topAnchor),
            slideView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            slideView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            slideView.heightAnchor.constraint(equalToConstant: 80)
        ])

只需尝试使用框架而不是约束..这段代码应该可以工作

  override func viewDidAppear(_ animated: Bool) {
        let slideView = UIView(frame: CGRect(x: 0, y:
            navigationController?.navigationBar.frame.height ?? 0 + 20 ,width: UIScreen.main.bounds.width, height: 80))

        slideView.backgroundColor = .red
        slideView.translatesAutoresizingMaskIntoConstraints = false

        view.backgroundColor = .white
        navigationItem.title = "Absensi"
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationController?.navigationBar.barTintColor = .white
        navigationController?.navigationBar.shadowImage  = UIImage()
        navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "NunitoSans-SemiBold", size: 20)]
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic-back-line").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleBack))

        view.addSubview(slideView)            
  }

设置关于安全区域的约束。

您应该将 topAnchor 添加到安全区域 -> view.safeAreaLayoutGuide.topAnchor

NSLayoutConstraint.activate([
    slideView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    slideView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    slideView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    slideView.heightAnchor.constraint(equalToConstant: 80)
])