nslayout 约束不使对象出现
nslayout constraint not making object appear
我下面的代码使用没有故事板的代码来显示对象。该项目已构建,但我看不到我试图以编程方式放置的文本字段。我不知道为什么代码没有出现。我试图不使用故事板。
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)
])
}
您需要将 translatesAutoresizingMaskIntoConstraints
设置为 false
:
enterWeight.translatesAutoresizingMaskIntoConstraints = false
您有相互冲突的约束,它们永远不会以这种方式工作。
首先,如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),所以你不应该给它一个宽度约束,会引起冲突。
我下面的代码使用没有故事板的代码来显示对象。该项目已构建,但我看不到我试图以编程方式放置的文本字段。我不知道为什么代码没有出现。我试图不使用故事板。
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)
])
}
您需要将 translatesAutoresizingMaskIntoConstraints
设置为 false
:
enterWeight.translatesAutoresizingMaskIntoConstraints = false
您有相互冲突的约束,它们永远不会以这种方式工作。
首先,如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),所以你不应该给它一个宽度约束,会引起冲突。