How to add constraints programmatically using Swift

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

    Constraints for multiple views in playground.

    swift 3+

      var yellowView: UIView!
        var redView: UIView!
    
        override func loadView() {
    
            // UI
    
            let view = UIView()
            view.backgroundColor = .white
    
            yellowView = UIView()
            yellowView.backgroundColor = .yellow
            view.addSubview(yellowView)
    
            redView = UIView()
            redView.backgroundColor = .red
            view.addSubview(redView)
    
            // Layout
            redView.translatesAutoresizingMaskIntoConstraints = false
            yellowView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                yellowView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
                yellowView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                yellowView.widthAnchor.constraint(equalToConstant: 80),
                yellowView.heightAnchor.constraint(equalToConstant: 80),
    
                redView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
                redView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -20),
                redView.widthAnchor.constraint(equalToConstant: 80),
                redView.heightAnchor.constraint(equalToConstant: 80)
                ])
    
            self.view = view
        }
    

    In my opinion xcode playground is the best place for learning adding constraints programmatically.

提交回复
热议问题