Evenly space multiple views within a container view

后端 未结 29 3097
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:14

Auto Layout is making my life difficult. In theory, it was going to be really useful when I switched, but I seem to fight it all of the time.

I\'ve made a demo proje

29条回答
  •  生来不讨喜
    2020-11-22 06:28

    swift 3 version

    let _redView = UIView()
            _redView.backgroundColor = UIColor.red
            _redView.translatesAutoresizingMaskIntoConstraints = false
    
            let _yellowView = UIView()
            _yellowView.backgroundColor = UIColor.yellow
            _yellowView.translatesAutoresizingMaskIntoConstraints = false
    
            let _blueView = UIView()
            _blueView.backgroundColor = UIColor.blue
            _blueView.translatesAutoresizingMaskIntoConstraints = false
    
            self.view.addSubview(_redView)
            self.view.addSubview(_yellowView)
            self.view.addSubview(_blueView)
    
            var views = ["_redView": _redView, "_yellowView": _yellowView, "_blueView":_blueView]
    
            var nslayoutConstraint_H = NSLayoutConstraint.constraints(withVisualFormat: "|->=0-[_redView(40)]->=0-[_yellowView(40)]->=0-[_blueView(40)]->=0-|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views)
            self.view.addConstraints(nslayoutConstraint_H)
    
            var nslayoutConstraint_V = NSLayoutConstraint.constraints(withVisualFormat: "V:[_redView(60)]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: views)
            self.view.addConstraints(nslayoutConstraint_V)
    
    
            let constraint_red = NSLayoutConstraint.init(item: self.view, attribute: .centerY, relatedBy: .equal, toItem: _redView, attribute: .centerY, multiplier: 1, constant: 0)
            self.view.addConstraint(constraint_red)
    
            let constraint_yellow = NSLayoutConstraint.init(item: self.view, attribute: .centerX, relatedBy: .equal, toItem: _yellowView, attribute: .centerX, multiplier: 1, constant: 0)
            self.view.addConstraint(constraint_yellow)
    
            let constraint_yellow1 = NSLayoutConstraint.init(item: _redView, attribute: .centerX, relatedBy: .equal, toItem: _yellowView, attribute: .leading, multiplier: 0.5, constant: 0)
            self.view.addConstraint(constraint_yellow1)
    
            let constraint_yellow2 = NSLayoutConstraint.init(item: _blueView, attribute: .centerX, relatedBy: .equal, toItem: _yellowView, attribute: .leading, multiplier: 1.5, constant: 40)
            self.view.addConstraint(constraint_yellow2)
    

提交回复
热议问题