Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Programmticaly Add AutoLayout by Visual Format Language in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 567
    Comment on it

    Auto layout adjusts the size and position of view according to the constraints applied to it. This approach dynamically changes our User Interface according to different screen sizes.
    There are different ways for adding autolayout programmatically. Here I am using visual format language to add a view.

    Let us create a View and add it to its superview.

        let currentView = UIView.init()
        
        currentView.backgroundColor = UIColor.red
        
        self.view.addSubview(currentView)
        
        currentView.translatesAutoresizingMaskIntoConstraints = false     
        let views = Dictionary(dictionaryLiteral: ("currentView",currentView))
     

    After creating a view apply constraints on it which will adjust its position and size.

     

    Now let set up its horizontal constraint, it will provide leading and trailing space to our view. Here I have added a view having 10 points leading and trailing edge from its superview.

       let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[currentView]-(10)-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
    
    self.view.addConstraints(horizontalConstraints)

     

    After adjusting leading and trailing space, adjust its top and bottom edge by adding vertical constraints.

     let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(10)-[currentView]-(10)-|", options: NSLayoutFormatOptions.alignAllCenterX, metrics: nil, views: views)
        self.view.addConstraints(verticalConstraints)
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: