提问者:小点点

游乐场中的NSLayoutConstraint


我试图重现这样一个场景,红色和蓝色矩形可以在不同的屏幕尺寸下占据相同的宽度和高度(以及它们之间的相同间隙)。

我正在使用NSLayoutConstraint(我知道现在首选锚,只是试图探索基础)。我在swift游乐场尝试了以下代码:

import Foundation
import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    var firstColorView:  UIView!
    var secondColorView: UIView!

    override func viewWillAppear(_ animated: Bool) {
        var myView: UIView!
        myView = view
        myView.backgroundColor = .white

        firstColorView = UIView()
        secondColorView = UIView()
        firstColorView.backgroundColor = .red
        secondColorView.backgroundColor = .blue

        myView.addSubview(firstColorView)
        myView.addSubview(secondColorView)


        //myView.translatesAutoresizingMaskIntoConstraints = false
        //view.addSubview(myView)

        //  horizontal constraints
        let left_constraint = NSLayoutConstraint(item: firstColorView, attribute: .leftMargin, relatedBy: .equal, toItem: myView, attribute: .left, multiplier: 1.0, constant: 20)
        let middle_constraint = NSLayoutConstraint(item: secondColorView, attribute: .leftMargin, relatedBy: .equal, toItem: firstColorView, attribute: .right, multiplier: 1.0, constant: 10)
        let right_constraint = NSLayoutConstraint(item: myView, attribute: .rightMargin, relatedBy: .equal, toItem: secondColorView, attribute: .right, multiplier: 1.0, constant: 20)
        let width_constraint = NSLayoutConstraint(item: firstColorView, attribute: .width, relatedBy: .equal, toItem: secondColorView, attribute: .width, multiplier: 1.0, constant: 0)

        // vertical constraints
        let top_constraint1 = NSLayoutConstraint(item: firstColorView, attribute: .top, relatedBy: .equal, toItem: myView, attribute: .top, multiplier: 1.0, constant: 10)
        let top_constraint2 = NSLayoutConstraint(item: secondColorView, attribute: .top, relatedBy: .equal, toItem: myView, attribute: .top, multiplier: 1.0, constant: 10)
        let bottom_constraint1 = NSLayoutConstraint(item: myView, attribute: .bottom, relatedBy: .equal, toItem: firstColorView, attribute: .bottom, multiplier: 1.0, constant: 10)
        let bottom_constraint2 = NSLayoutConstraint(item: myView, attribute: .bottom, relatedBy: .equal, toItem: secondColorView, attribute: .bottom, multiplier: 1.0, constant: 0)

        NSLayoutConstraint.activate([left_constraint, middle_constraint, right_constraint, width_constraint, top_constraint1, top_constraint2, bottom_constraint1, bottom_constraint2])
        self.view.layoutIfNeeded()
    }
}


// Present the view controller in the Live View window
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = MyViewController()

但它显示的只是一个白色屏幕,其宽度与iPhone不匹配。我在这里做错了什么?为什么我看不到红蓝屏?


共1个答案

匿名用户

你错过了

firstColorView.translatesAutoresizingMaskIntoConstraints = false  
secondColorView.translatesAutoresizingMaskIntoConstraints = false