我下面的代码使用没有故事板的代码来显示对象。该项目已建立,但我看不到我试图以编程方式放置的文本字段。我不知道为什么代码没有出现。我试图不使用情节提要。
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)
])
}
答案 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),所以您不应该给它一个宽度约束,它会引起冲突。