swiftuikit

How to prevent navigation title from moving up and down while showing a sheet?


When I move the sheet up and down, the navigation title does not stay in place but moves up and down as well. How can I make it stay in the initial place ?

class ViewController: UIViewController {
    
    class SheetViewController: UIViewController {
        override func viewDidLoad() {
            self.view.backgroundColor = .systemBlue
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .black
        self.navigationItem.title = "Hello, World!"
        
        let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
        navigationController?.navigationBar.titleTextAttributes = textAttributes
    }
    
    @IBAction func openSheet(_ sender: Any) {
        let viewControllerToPresent = SheetViewController()
        if let sheet = viewControllerToPresent.sheetPresentationController {
            sheet.detents = [.large()]
            present(viewControllerToPresent, animated: true, completion: nil)
        }
    }
}

enter image description here


Solution

  • To prevent the navigation title from moving downwards, you should use a .custom detent that is smaller than the maximum detent height.

    sheet.detents = [.custom { context in
        context.maximumDetentValue - 1
    }]
    

    If you want the navigation title to be completely visible and not covered by the sheet, you should subtract the height of the navigation bar from the maximum detent height.

    sheet.detents = [.custom { [weak self] context in
        context.maximumDetentValue - (self?.navigationController?.navigationBar.frame.height ?? 0)
    }]
    

    If the keyboard can be shown when the sheet is displayed, it might push the sheet upwards, and cause the navigation title to move downwards. If that is a concern, you should also take into account the keyboard height, and subtract that as well, in addition to the navigation bar height.

    Remember to also invalidateDetents if the navigation bar height or keyboard height changes while the sheet is presented.