How to add constraints programmatically using Swift

前端 未结 17 1179
逝去的感伤
逝去的感伤 2020-11-21 23:07

I\'m trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically

相关标签:
17条回答
  • 2020-11-21 23:38

    Auto layout is realized by applying constraints on images. Use NSLayoutConstraint. It is possible to implement an ideal and beautiful design on all devices. Please try the code below.

    import UIKit
    
    class ViewController: UIViewController {
    
    override func viewDidLoad() {
    super.viewDidLoad()
    
    let myImageView:UIImageView = UIImageView()
    myImageView.backgroundColor = UIColor.red
    myImageView.image = UIImage(named:"sample_dog")!
    myImageView.translatesAutoresizingMaskIntoConstraints = false
    myImageView.layer.borderColor = UIColor.red.cgColor
    myImageView.layer.borderWidth = 10
    self.view.addSubview(myImageView)
            
    view.removeConstraints(view.constraints)
    
    
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .top,
    relatedBy: .equal,
    toItem: view,
    attribute: .top,
    multiplier: 1,
    constant:100)
        
    )
    
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .centerX,
    relatedBy: .equal,
    toItem: view,
    attribute: .centerX,
    multiplier: 1,
    constant:0)
    )
        
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .height,
    relatedBy: .equal,
    toItem: view,
    attribute: .width,
    multiplier: 0.5,
    constant:40))
        
    view.addConstraint(NSLayoutConstraint(
    item: myImageView,
    attribute: .width,
    relatedBy: .equal,
    toItem: view,
    attribute: .width,
    multiplier: 0.5,
    constant:40))
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    }
    

    0 讨论(0)
  • 2020-11-21 23:39

    it is a little different in xcode 7.3.1. this is what i come up with

       // creating the view
            let newView = UIView()
            newView.backgroundColor = UIColor.redColor()
            newView.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(newView)
    
            // creating the constraint 
    
            // attribute and relation cannot be set directyl you need to create a cariable of them
            let layout11 = NSLayoutAttribute.CenterX
            let layout21 = NSLayoutRelation.Equal
            let layout31 = NSLayoutAttribute.CenterY
            let layout41 = NSLayoutAttribute.Width
            let layout51 = NSLayoutAttribute.Height
            let layout61 = NSLayoutAttribute.NotAnAttribute
    
            // defining all the constraint
            let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: layout11, relatedBy: layout21, toItem: view, attribute: layout11, multiplier: 1, constant: 0)
            let verticalConstraint = NSLayoutConstraint(item: newView, attribute: layout31, relatedBy: layout21, toItem: view, attribute: layout31, multiplier: 1, constant: 0)
            let widthConstraint = NSLayoutConstraint(item: newView, attribute: layout41, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100)
            let heightConstraint = NSLayoutConstraint(item: newView, attribute: layout51, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100)
    
            // adding all the constraint
            NSLayoutConstraint.activateConstraints([horizontalConstraint,verticalConstraint,widthConstraint,heightConstraint])
    
    0 讨论(0)
  • 2020-11-21 23:39

    If you find the above to be ugly. You should consider using a DSL for constraints. Such as SnapKit Makes constraint API much more user-friendly

    view.snp.makeConstraints { make in
        make.edges.equalToSuperview()
    }
    
    0 讨论(0)
  • 2020-11-21 23:40

    Basically it involved 3 steps

    fileprivate func setupName() { 
    
        lblName.text = "Hello world"
    
        // Step 1
        lblName.translatesAutoresizingMaskIntoConstraints = false
    
        //Step 2
        self.view.addSubview(lblName)
    
        //Step 3
        NSLayoutConstraint.activate([
            lblName.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            lblName.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
    }
    

    This puts label "hello world" in center of screen.

    Please refer link Autolayout constraints programmatically

    0 讨论(0)
  • 2020-11-21 23:44

    The error is caused by constrains automatically created from autoresizing mask, they are created because UIView property translatesAutoresizingMaskIntoConstraints is true by default.

    Consider using BoxView to get rid of all manual constraint creation boilerplate, and make your code concize and readable. To make layout in question with BoxView is very easy:

    boxView.items = [
       new_view.boxed.centerX().centerY().relativeWidth(1.0).relativeHeight(1.0)
    ]
    
    0 讨论(0)
提交回复
热议问题