以编程方式按钮自动布局?
Button Autolayout programmatically?
大家好,我想将我的按钮放在屏幕的下部,但我没有得到正确的代码。按钮太小,太大,在右上角或左下角,...但应该在下屏中间居中。
我用这些代码试过了:
nextButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
nextButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 97)
nextButton.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 50)
或
backButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
backButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
backButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
谁能告诉我该怎么做才能让它发挥作用?我认为使用 topAnchor 会很简单:(
这会将其定位在屏幕的底部中央
nextButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
nextButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant:-20),
nextButton.widthAnchor.constraint(equalToConstant: 50),
nextButton.heightAnchor.constraint(equalToConstant: 50)
])
问题是您使用的是 centerYAnchor 而不是 bottomAnchor
替换
nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
和
let spacingConstant = 10.0
nextButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -spacingConstant)
大家好,我想将我的按钮放在屏幕的下部,但我没有得到正确的代码。按钮太小,太大,在右上角或左下角,...但应该在下屏中间居中。
我用这些代码试过了:
nextButton.translatesAutoresizingMaskIntoConstraints = false
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
nextButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 97)
nextButton.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 50)
或
backButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
backButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
backButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
backButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
谁能告诉我该怎么做才能让它发挥作用?我认为使用 topAnchor 会很简单:(
这会将其定位在屏幕的底部中央
nextButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
nextButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant:-20),
nextButton.widthAnchor.constraint(equalToConstant: 50),
nextButton.heightAnchor.constraint(equalToConstant: 50)
])
问题是您使用的是 centerYAnchor 而不是 bottomAnchor
替换
nextButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
和
let spacingConstant = 10.0
nextButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -spacingConstant)