How to add constraints programmatically using Swift

前端 未结 17 1166
逝去的感伤
逝去的感伤 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:32

    Updated for Swift 3

    import UIKit
    
    class ViewController: UIViewController {
    
    let redView: UIView = {
    
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .red
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupViews()
        setupAutoLayout()
    }
    
    func setupViews() {
    
        view.backgroundColor = .white
        view.addSubview(redView)
    }
    
    func setupAutoLayout() {
    
        // Available from iOS 9 commonly known as Anchoring System for AutoLayout...
        redView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
        redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true
    
        redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        redView.heightAnchor.constraint(equalToConstant: 300).isActive = true
    
        // You can also modified above last two lines as follows by commenting above & uncommenting below lines...
        // redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
        // redView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
     }
    }
    

    Type of Constraints

     /*
    // regular use
    1.leftAnchor
    2.rightAnchor
    3.topAnchor
    // intermediate use
    4.widthAnchor
    5.heightAnchor
    6.bottomAnchor
    7.centerXAnchor
    8.centerYAnchor
    // rare use
    9.leadingAnchor
    10.trailingAnchor
    etc. (note: very project to project)
    */
    

提交回复
热议问题