nslayout约束不使对象出现

时间:2019-02-14 21:44:51

标签: ios swift4 nslayoutconstraint subview

我下面的代码使用没有故事板的代码来显示对象。该项目已建立,但我看不到我试图以编程方式放置的文本字段。我不知道为什么代码没有出现。我试图不使用情节提要。

 var enterWeight = UITextField()




override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(enterWeight)

    enterWeight.backgroundColor = UIColor.blue


    NSLayoutConstraint.activate ([

        enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
        enterWeight.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant : 20),
        enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
        enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),


        enterWeight.widthAnchor.constraint(equalToConstant: 50),
        enterWeight.heightAnchor.constraint(equalToConstant: 30)

        ])

}

2 个答案:

答案 0 :(得分:0)

您需要将translatesAutoresizingMaskIntoConstraints设置为false

enterWeight.translatesAutoresizingMaskIntoConstraints = false

答案 1 :(得分:0)

您有相互矛盾的约束,它们永远不会以这种方式工作。

首先,如iFlames所述,您需要将translatesAutoresizingMaskIntoConstraints设置为false

enterWeight.translatesAutoresizingMaskIntoConstraints = false

然后:

NSLayoutConstraint.activate ([
        enterWeight.topAnchor.constraint(equalTo: view.topAnchor, constant : 20),
        enterWeight.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 20),
        enterWeight.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : 20),
        enterWeight.heightAnchor.constraint(equalToConstant: 30)
])

通过给textField一个前导和尾随,您已经暗含了宽度约束,它是view的宽度减去常数(20 * 2),所以您不应该给它一个宽度约束,它会引起冲突。