Monday, April 1, 2019

The View's Margins in iOS

The top, leading, bottom, and trailing margins of a view define the spaces between the view's edges and its contents.



Setting layout margins in Interface Builder


The margins can be set in Interface Builder by updating the Layout Margins setting (in Size Inspector) to either Language Directional or Fixed then specify the values for Leading, Top, Bottom, and Trailing edges.


Then, we can create a constraint for the subview's edges relative to superview's margins as following:


Note that if we don't check the "Constraint to margins", it means we constraint the subview's edges relatively to its superview's edges, not the layout margins.



Setting layout margins programmatically


Open the ViewController.swift file and update the viewDidLoad() method as following:
    
import UIKit

class SecondViewController: UIViewController {
    
    @IBOutlet weak var view1: UIView!
    
    override func viewDidLoad() {
        let layoutMarginGuide = self.view.layoutMarginsGuide
        view1.leadingAnchor.constraint(equalTo: layoutMarginGuide.leadingAnchor).isActive = true
        view1.topAnchor.constraint(equalTo: layoutMarginGuide.topAnchor).isActive = true
        view1.trailingAnchor.constraint(equalTo: layoutMarginGuide.trailingAnchor).isActive = true
        view1.bottomAnchor.constraint(equalTo: layoutMarginGuide.bottomAnchor).isActive = true
        view1.translatesAutoresizingMaskIntoConstraints = false
    }
}
    



No comments:

Post a Comment