Search code examples
objective-cswiftxcodeioautolayout

Adding constraints to a ViewController secondary UIView


I have a Storyboard setup with a dialog box that utilizes a secondary UIView (yellow in the screenshot.) This is done by dragging a UIView from the objects library up in between First Responder and Exit on the Storyboard.

I can't figure out how to add basic constraints to this secondary UIView relative to the superview. Right click and dragging won't let me apply constraints. Is this possible? Do I need to handle all Autolayout / constraints programmatically?

I just need to add constraints from leading / trailing. Height will be fixed, but may adjust accordingly depending on screen size.

Secondary view.


Solution

  • This has been figured out. You can not use right-click & drag constraints in IB on these views. Why?? Because they're not a part of the view hierarchy yet! (silly me..)

    In my above example with the yellow secondary view, here's how you would apply auto layout to it using VFL (Visual Format Language).

    In ViewDidLoad, you first want to turn off the views auto resizing mask:

    self.yellowSecondaryView.translatesAutoresizingMaskIntoConstraints = false
    

    Now find where you're adding the subview. Let's say you use a button action to trigger it... Inside that action, you first add the view (1), and then the constraints (2):

    // 1
    view.addSubview(yellowSecondaryView)
    
    // Create a string representation of the view to use it with VFL.
    let viewsDictionary: [String: UIView] = ["yellowSecondaryView": yellowSecondaryView]
    
    //2
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[yellowSecondaryView]-50-|", options: [], metrics: nil, views: viewsDictionary))  // Width of yellow view will be full width, minus 50 points from the LEFT and the RIGHT of the superview (|)
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[yellowSecondaryView(250)]", options: [], metrics: nil, views: viewsDictionary)) // Set a static height of 250 for the yellow view
    
    view.addConstraint(NSLayoutConstraint(item: yellowSecondaryView, attribute: .centerY, relatedBy: NSLayoutRelation(rawValue: 0)!, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))  // Center the view vertically in the superview. (credit to @rdelmar in this thread: http://stackoverflow.com/questions/21494039/using-autolayout-in-ib-how-do-i-position-a-uiview-in-the-center-of-the-screen-pr/21494707#21494707)
    

    Hope this helps somebody create a much more manageable and organized storyboard! :)