答案 0 :(得分:3)
假设您的标签和按钮都没有固定的宽度和高度。
然后你的代码看起来就像这样。只是提到我使用LayoutAnchor很容易。
func autolayoutTitle() {
let label = UILabel()
label.backgroundColor = UIColor.red
label.textColor = UIColor.white
label.text = "Nafeez Zawahir"
label.textAlignment = .right
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
//label.widthAnchor.constraint(equalToConstant: 150).isActive = true
// label.heightAnchor.constraint(equalToConstant: 40).isActive = true
label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
let button = UIButton()
//button.titleLabel?.text = "Follow"
button.setTitle("Follow", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor = UIColor.darkGray
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
// button.widthAnchor.constraint(equalToConstant: 100).isActive = true
// button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.leftAnchor.constraint(equalTo: label.rightAnchor, constant: 2).isActive = true
button.lastBaselineAnchor.constraint(equalTo: label.lastBaselineAnchor).isActive = true
// button.lastBaselineAnchor.constraint(equalTo: label.lastBaselineAnchor, constant: -10).isActive = true
}
输出是:
但是,如果您的标签以及按钮也固定了宽度和高度,那么您必须调整按钮的基线锚定使用标签的基线锚点,这取决于标签的高度。
假设你有这样的标签高度40。
label.heightAnchor.constraint(equalToConstant: 40).isActive = true
然后你的按钮的基线锚定应该是这样的。
button.lastBaselineAnchor.constraint(equalTo: label.lastBaselineAnchor, constant: -10).isActive = true
以下是代码:
func autolayoutTitle() {
let label = UILabel()
label.backgroundColor = UIColor.red
label.textColor = UIColor.white
label.text = "Nafeez Zawahir"
label.textAlignment = .right
view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.widthAnchor.constraint(equalToConstant: 150).isActive = true
label.heightAnchor.constraint(equalToConstant: 40).isActive = true
label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
let button = UIButton()
//button.titleLabel?.text = "Follow"
button.setTitle("Follow", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.backgroundColor = UIColor.darkGray
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 100).isActive = true
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.leftAnchor.constraint(equalTo: label.rightAnchor, constant: 2).isActive = true
// button.lastBaselineAnchor.constraint(equalTo: label.lastBaselineAnchor).isActive = true
button.lastBaselineAnchor.constraint(equalTo: label.lastBaselineAnchor, constant: -10).isActive = true
}
这是输出: