iosobjective-cconstraintsuinavigationbarvisual-format-language

Is there a way to use Visual Format Language to constrain a view to the bottom of a navigation bar?


I'm currently trying to vertically position a view right underneath the navigation bar. However, I'm trying to use Visual Format Language to do this.

I have essentially 3 views: let's call them a, b, c

My current code to do this is:

 @"V:|-dist-[a][b][c]|"

I basically have to set the "dist" to the height of the navigation bar. Otherwise the subview "a" will be above the navigation bar since the superview is into the safe area.

Even though I could essentially use this solution, the problem lies on designing for different screens where the size of the navigation bar is different. I tried to grab the navigation bar height:

CGFloat topbarHeight = self.navigationController.navigationBar.frame.size.height;

But it returns:

error: property 'navigationBar' not found on object of type 'id'

I assume this is because the view has not loaded yet? And it can't recognize the navigation bar? Ideally I would love if there was some sort of symbol that represented the navigationbar default area. Similar to the "|" symbol representing a superview in Visual Format Language.

Any help would be appreciated.


Solution

  • You can set the top constraint to UIViewController.view if you are setting edgesForExtendedLayout = [], this will keep the view of your UIViewController just below of your navigation bar

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.edgesForExtendedLayout = []
        let view = UIView(frame: .zero)
        view.backgroundColor = UIColor.red
        view.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(view)
    
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view":view]));
        self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view(50)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view":view]));
    }
    

    Result

    enter image description here